Why?
I was assigned a duty to develop a RESTful API for my company. And I was like, why not try out the new .NET Core. So I started an MVC Web API project. No surprise, it was similar to .NET 4.5+. Single
Get
or Post
method for each controller. But I wanted a service controller with several get
methods for customer.
Let's get to it.
Instead of modifying the webapiconfig, the
Route
options is directly in the controller
class.
Hide Shrink Copy Code
//
// Default generated controller
//
[Route("api/[controller]")
public class myApiController : Controller
{
[HttpGet]
public string GetInfo()
{
return "Information";
}
}
//
//A little change would do the magic
//
[Route("api/{controller}/{action}")]
public class ServicesController : Controller
{
[HttpGet]
[ActionName("Get01")]
public string Get01()
{
return "GET 1";
}
[HttpGet]
[ActionName("Get02")]
public string Get02()
{
return "Get 2";
}
[HttpPost]
[ActionName("Post01")]
public HttpResponseMessage Post01(MyCustomModel01 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
[HttpPost]
[ActionName("Post02")]
public HttpResponseMessage Post02(MyCustomModel02 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
}
//
That's it. Hope this will help someone.
No comments:
Post a Comment