Return content with IHttpActionResult for non-OK response

前端 未结 15 2173
北恋
北恋 2020-11-28 17:55

For returning from a Web API 2 controller, I can return content with the response if the response is OK (status 200) like this:

    public IHttpActionResult          


        
15条回答
  •  抹茶落季
    2020-11-28 18:34

    A more detailed example with support of HTTP code not defined in C# HttpStatusCode.

    public class MyController : ApiController
    {
        public IHttpActionResult Get()
        {
            HttpStatusCode codeNotDefined = (HttpStatusCode)429;
            return Content(codeNotDefined, "message to be sent in response body");
        }
    }
    

    Content is a virtual method defined in abstract class ApiController, the base of the controller. See the declaration as below:

    protected internal virtual NegotiatedContentResult Content(HttpStatusCode statusCode, T value);
    

提交回复
热议问题