how to return json error msg in asp.net web api?

后端 未结 5 1664
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 21:14

I would like to return a json errormessage but at the moment in fiddler I cannot see this in the json panel:

string error = \"An error just happened\";
JsonResul         


        
5条回答
  •  太阳男子
    2021-02-03 22:04

    A few points:

    If all you're looking to do is return an error response containing a simple error message, Web API provides a CreateErrorResponse method for that. So you can simply do:

    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, 
                                       "An error just happened");
    

    This will result in the following HTTP response (other headers omitted for brevity):

    HTTP/1.1 400 Bad Request
    Content-Type: application/json; charset=utf-8
    Content-Length: 36
    
    {"Message":"An error just happened"}
    

    If you want to return a custom object instead, then you use Request.CreateResponse like you were doing, but don't use the MVC JsonResult. Instead, just pass your object directly to CreateResponse:

    var myError = new
    {
        Data = "An error just happened",
        OtherDetails = "foo bar baz"
    };
    
    return Request.CreateResponse(HttpStatusCode.BadRequest, myError);
    

    Now, say you are doing this but you're not getting JSON back from the server. It is important to realize that Web API normally uses content type negotiation to determine what format to use when sending the response back. That means, it looks at the Accept header that was sent by the client with the request. If the Accept header contains application/xml, for example, then Web API will return XML. If the header contains application/json then it will return JSON. So, you should check that your client is sending the correct Accept header.

    That said, there are ways to force Web API to always return data in a specific format if that is what you really want. You can do this at the method level by using a different overload of CreateResponse which also specifies the content type:

    return Request.CreateResponse(HttpStatusCode.BadRequest, myError, 
        new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
    

    Alternatively, you can remove the XML formatter from the configuration altogether in your WebApiConfig file:

    config.Formatters.Remove(config.Formatters.XmlFormatter);
    

    This will force Web API to always use JSON regardless of what the client asks for.

提交回复
热议问题