IHttpActionResult and helper methods in ASP.NET Core
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 ?
Solution 1:
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
Solution 2:
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);
}
Solution 3:
At 2.2, the ASP.NET Core migration guide states to replace IHttpActionResult with ActionResult. This works for me:
[Produces("application/json")]
[HttpPost]
public ActionResult GetSomeTable([FromBody] GridState state)
{
return Ok(new
{
data = query.ToList(),
paging = new
{
Total = total,
Limit = state.limit,
page = state.page,
Returned = query.Count()
}
});
}