WebApiCompatShim - how to configure for a REST api with MVC 6

前端 未结 2 547
甜味超标
甜味超标 2021-01-22 00:35

I was having a look at this link that shows how to migrate from Web API 2 to MVC 6.

I am trying to have Action methods in my controllers with the HttpRequestMessag

2条回答
  •  走了就别回头了
    2021-01-22 00:50

    In MVC6, You should be able to use the Request object to get header information.

    var contentTypeHeader = Request.Headers["Content-Type"];
    

    It is true that they removed some of the nice methods like Request.CreateResponse() and OK() etc.. But there are some alternatives you can use.

    All of these classes we will be using to create a response are inheriting from the ObjectResult base class. So you can use ObjectResult as the return type of your Web api method.

    HttpOKObjectResult

    In MVC6, You can use create an object of HttpOKObjectResult class and use that as your return value instead of Request.CreateResponse(). This will produce the status code 200 OK for the response.

    Web API2 code

    public HttpResponseMessage Post([FromBody]string value)
    {
        var item = new { Name= "test", id = 1 };
        return Request.CreateResponse(HttpStatusCode.OK,item);
    }
    

    MVC 6 code

    [HttpPost]
    public ObjectResult Post([FromBody]string value)
    {
        var item = new {Name= "test", id=1};
        return new HttpOkObjectResult(item);
    }
    

    Or simply use the OK() method.

    [HttpPost]
    public ObjectResult Post([FromBody]string value)
    {
        var item = new {Name= "test", id=1};
        return Ok(item);
    }
    

    CreatedAtRouteResult

    You can use CreatedAtRouteResult class to send a response with 201 Created status code with a location header.

    MVC 6 code

    [HttpPost]
    public ObjectResult Post([FromBody]string value)
    {
        var item = new { Name= "test", id=250};
        return new CreatedAtRouteResult(new { id = 250}, item);
    }
    

    The client will receive a location header in the response which will point to the api route with 250 as the value for the id parameter.

    HttpNotFoundObjectResult

    You can use this class to return a 404 Not found response.

    Web API2 code

    public HttpResponseMessage Post([FromBody]string value)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound);   
    }
    

    MVC 6 code

    [HttpPost]
    public ObjectResult Post([FromBody]string value)
    {
        return new HttpNotFoundObjectResult("Some");
    }
    

提交回复
热议问题