Web API Best Approach for returning HttpResponseMessage

后端 未结 3 1145
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  -上瘾入骨i
    2021-02-03 22:17

    Although this is not directly answering the question, I wanted to provide some information I found usefull. http://weblogs.asp.net/dwahlin/archive/2013/11/11/new-features-in-asp-net-web-api-2-part-i.aspx

    The HttpResponseMessage has been more or less replaced with IHttpActionResult. It is much cleaner an easier to use.

    public IHttpActionResult Get()
    {
         Object obj = new Object();
         if (obj == null)
             return NotFound();
         return Ok(obj);
     }
    

    Then you can encapsulate to create custom ones. How to set custom headers when using IHttpActionResult?

    I haven't found a need yet for implementing a custom result yet but when I do, I will be going this route.

    Its probably very similar to do using the old one as well.

    To expand further on this and provide a bit more info. You can also include messages with some of the requests. For instance.

    return BadRequest("Custom Message Here");
    

    You can't do this with many of the other ones but helps for common messages you want to send back.

提交回复
热议问题