.Net Core MVC Controllers Migration

Chewy2Theo
1 min readMay 29, 2021

The controllers are easy to migrate but I’ll document it anyways just to clear out the unknowns.

This is how I used to return HttpResponseMessage in .Net

return Request.CreateResponse(HttpStatusCode.OK);

And now this is how it’s changed to

return new HttpResponseMessage(HttpStatusCode.OK);

However, the statement doesn’t contain a parameter to return a json response, so it’s used to return pure http status code. To include a json response, use IActionResult

[HttpGet]
[Route("api/abc")]
[Authorize(Roles = "SomeRole")]
public IActionResult Get()
{
return new OkObjectResult(response);
// or return Ok(response);
}

You can also use BadRequest to return a 400 instead of creating a new HttpResponseMessage

return BadRequest(new { message = "Login is invalid"});

To receive a json request in the body, the attribute is still the same

[HttpPost]
public HttpResponseMessage Post([FromBody] PostModel model)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}

To retrieve a variable from the url is no longer through FromUri, it is now FromRoute

[HttpGet]
[Route("api/something/{id}/anotherthing")]
public HttpResponseMessage Get([FromRoute]int id)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}

And to retrieve query parameters, use FromQuery

[HttpGet]
[Route("api/something")]
public IActionResult Get([FromQuery]QueryModel request)
{
return new OkObjectResult(response);
}

The aboves changes are rather simple but can still be time consuming if you have a larger code base.

This article is a part of the .Net to .Net Core Migration Series
https://theochiu2010.medium.com/net-to-net-core-migration-2eb31584f95c

--

--

Chewy2Theo

Just another developer who's into lazy tools that can make my life easier, and hopefully yours too.