Web API Best Approach for returning HttpResponseMessage

后端 未结 3 1146
隐瞒了意图╮
隐瞒了意图╮ 2021-02-03 22:01

I have a Web API project and right my methods always returns HttpResponseMessage.

So, if it works or fails I return:

No errors:

3条回答
  •  深忆病人
    2021-02-03 22:03

    You can return an error response to provide more detail.

    public HttpResponseMessage Get()
    {
        HttpError myCustomError = new HttpError("The file has no content or rows to process.") { { "CustomErrorCode", 42 } };
         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, myCustomError);
     }
    

    Would return:

    { 
      "Message": "The file has no content or rows to process.", 
      "CustomErrorCode": 42 
    }
    

    More details here: http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

    I also use http://en.wikipedia.org/wiki/List_of_HTTP_status_codes to help me determine what http status code to return.

提交回复
热议问题