使用 JArray 发送自定义错误状态代码



我有webapi,它返回JArray。有什么方法可以使用我选择的一些状态代码(如 422、4XX)发送响应?

        //GET api/UserControl/GetUserName
    public JArray GetUserName()
    {
        JArray json = new JArray();
        try
        {
            string UserID= getUserID();
            if (!string.IsNullOrEmpty(UserID) || UserID== "None Was found")
            {
                var result = JsonConvert.SerializeObject(donorRep.GetUserFullName(UserID), Formatting.None,
                  new JsonSerializerSettings()
                  {
                      ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                  });
                try
                {
                    json = JArray.Parse(result);
                }
                catch
                {
                    json.Add(result.ToString());
                }
            }
            else
            {
                json.Add("There was an issue while retrieving your UserID.");
            }
        }
        catch (JsonSerializationException ex)
        {
            json.Add("There was an issue while retrieving your IDSID. Please contact support");
        }
        return json;
    }

例如,如果这里有一个错误,而不是在UI中:

 json.Add("There was an issue while retrieving your UserID");

数组包装在 JSON 对象中,然后为状态代码和可能需要的任何其他"元"信息添加其他属性。 例如,您可以尝试使 JSON 响应如下所示:

{
    "statusCode" : 422
    "errorMessage" : "Error message, if any, goes here."
    "results" : [
        "item 1",
        "item 2",
        "etc.",
        "you can also use objects here instead of strings if your data is more complex"
    ]
}

然后使你的代码像这样:

// GET api/UserControl/GetUserName
public JObject GetUserName()
{
    JArray resultArray = new JArray();
    int statusCode = 200;  // success
    string errorMessage = null;
    try
    {
        string UserID= getUserID();
        if (!string.IsNullOrEmpty(UserID))
        {
            var fullName = donorRep.GetUserFullName(UserID);
            resultArray.Add(fullName);
        }
        else
        {
            statusCode = 421;  // error
            errorMessage = "There was an issue while retrieving your UserID.";
        }
    }
    catch (Exception ex)
    {
        statusCode = 422;  // error
        errorMessage = "There was an issue while retrieving your IDSID. Please contact support.";
    }
    JObject response = new JObject();
    response.Add("statusCode", statusCode);
    response.Add("errorMessage", errorMessage);
    response.Add("results", resultArray);
    return response;
}

您必须调整客户端代码才能提取响应的各个部分。 例如,如果你使用的是jQuery,你可以得到这样的数据:

$.get("/api/UserControl/GetUserName")
 .done(function(data) {
     var statusCode = data.statusCode;
     if (statusCode == 200) {
         var userName = data.results[0];
         alert("Success!  User name is " + userName);
     }
     else {
         alert("Failed with code " + statusCode + ". message: " + data.errorMessage);         
     }
 });

为了完整起见,我还应该提到,在Web API中,您不必使用JObjects,JArrays等手动构建JSON。 作为替代方法,可以使用强类型类并直接从方法返回这些类,Web API 会为您将它们序列化为 JSON。 当然,类的结构必须与要返回的 JSON 匹配。 例如,如果要执行此方法,则可以定义如下所示的类:

class ResponseData
{
    public int statusCode { get; set; }
    public string errorCode { get; set; }
    public List<string> results { get; set; }
    public ResponseData() 
    {
        results = new List<string>();
    }
}

然后你可以做:

public ResponseData GetUserName()
{
    ResponseData response = new ResponseData { statusCode = 200 };
    try
    {
        string userID = getUserID();
        if (!string.IsNullOrEmpty(UserID))
        {
            var fullName = donorRep.GetUserFullName(UserID);
            response.results.Add(fullName);
        }
        else
        {
            response.statusCode = 421;  // error
            response.errorMessage = "There was an issue while retrieving your UserID.";
        }
    }
    catch (Exception ex)
    {
        response.statusCode = 422;  // error
        response.errorMessage = "There was an issue while retrieving your IDSID. Please contact support.";
    }
    return response;
}

相关内容

  • 没有找到相关文章

最新更新