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

时间:2016-03-06 12:11:00

标签: json asp.net-web-api json.net

我有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;
    }

例如,如果此处出现错误,则显示错误:

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

1 个答案:

答案 0 :(得分:0)

将数组包装在JSON对象中,然后为状态代码和任何其他" meta"添加其他属性。您可能需要的信息。例如,您可能会尝试使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中,您不必使用JObject,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;
}