Return JsonResult from web api without its properties

前端 未结 4 2061
日久生厌
日久生厌 2021-01-31 10:34

I have a Web API controller and from there I\'m returning an object as JSON from an action.

I\'m doing that like this:

public ActionResult GetAllNotifica         


        
4条回答
  •  面向向阳花
    2021-01-31 11:10

    As someone who has worked with ASP.NET API for about 3 years, I'd recommend returning an HttpResponseMessage instead. Don't use the ActionResult or IEnumerable!

    ActionResult is bad because as you've discovered.

    Return IEnumerable<> is bad because you may want to extend it later and add some headers, etc.

    Using JsonResult is bad because you should allow your service to be extendable and support other response formats as well just in case in the future; if you seriously want to limit it you can do so using Action Attributes, not in the action body.

    public HttpResponseMessage GetAllNotificationSettings()
    {
        var result = new List();
        // Filling the list with data here...
    
        // Then I return the list
        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
    

    In my tests, I usually use the below helper method to extract my objects from the HttpResponseMessage:

     public class ResponseResultExtractor
        {
            public T Extract(HttpResponseMessage response)
            {
                return response.Content.ReadAsAsync().Result;
            }
        }
    
    var actual = ResponseResultExtractor.Extract>(response);
    

    In this way, you've achieved the below:

    • Your Action can also return Error Messages and status codes like 404 not found so in the above way you can easily handle it.
    • Your Action isn't limited to JSON only but supports JSON depending on the client's request preference and the settings in the Formatter.

    Look at this: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

提交回复
热议问题