I'm trying to move my web api 2 project to ASP.NET 5. But I have many elements that are not present anymore.
For example IHttpActionResult
or Ok(), NotFound()
methods. Or RoutePrefix
[]
Should I change every IHttpActionResult
with IActionResult
? Change Ok
() with new ObjectResult
? (is it the same ?)
What about HttpConfiguration
that seems no more present in startup.cs ?
IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.
What is the difference between IHttpActionResult and IActionresult ? "IActionResult is the new abstraction that should be used in your actions. Since Web API and MVC frameworks have been unified in ASP.NET Core, various IActionResult implementations can handle both traditional API scenarios.".
HttpResponseMessage is used when we want to customize the return type (action result) of an action method. Responses are customized by providing status code, content type, and data to be returned to HttpResponseMessage.
IHttpActionResult
is now effectively IActionResult
, and to return an Ok
with a return object, you'd use return new ObjectResult(...);
So effectively something like this:
public IActionResult Get(int id) { if (id == 1) return HttpNotFound("not found!"); return new ObjectResult("value: " + id); }
Here's a good article with more detail:
http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6
Updated reply-ish
I saw that someone referenced the WebApiCompatShim
in a comment.
WebApiCompatShim
is still maintained for this kind of portability scenarios and it is now released 1.1.0.
I saw that Microsoft.AspNetCore.OData 1.0.0-rtm-00011
has WebApiCompatShim
as a dependency. I don't know exactly what they are trying to achieve in this area, these are just facts.
If you're not into getting another compatibility package and you're looking into more refactoring work, you can look at the following approach: WebApiCompatShim - how to configure for a REST api with MVC 6
You will still be able to use Ok()
or you can try to use the OkObjectResult()
method as Http word was removed in order not to be too verbose. HttpOkObjectResult
-> OkObjectResult
[HttpPost] public ObjectResult Post([FromBody]string value) { var item = new {Name= "test", id=1}; return new OkObjectResult(item); } [HttpPost] public ObjectResult Post([FromBody]string value) { var item = new {Name= "test", id=1}; return Ok(item); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With