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
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.
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);
}
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.
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");
}
I found that to use the Microsoft.AspNetCore.Mvc.WebApiCompatShim, it should be services.AddMvc().AddWebApiConventions()
see this example instead of services.AddWebApiConventions()
as shown in the docs.
I'm putting in a feedback item on their docs.