How to override Controller's name in asp.net mvc core?

1.9k Views Asked by At

In my MVC controller, i have two action methods which are rendering View, other 6 Action Methods are either HttpGet or HttpPost. I want to do the below

for ActionMethods rendering View it will be "controller/action". But for the GET/POST, i want it to be api/whatevernameilike.

Is it acheivable in asp.net mvc core?

TIA

3

There are 3 best solutions below

1
pouya On

You can use route attribute on top of your controller ex:

[Route("Api/Yourchosenname")]
public async Task<IActionResult> Action()
{
    return Ok();
}
2
feihoa On

Worth trying as well if the previous methods aren't working:

[HttpGet("/api/whatevernameilike")]
0
tmaj On

Attribute Routing in ASP.NET Web API 2 has an example for this:

Use a tilde (~) on the method attribute to override the route prefix:

[RoutePrefix("api/books")]
public class BooksController : ApiController
{
    // GET /api/authors/1/books
    [Route("~/api/authors/{authorId:int}/books")]
    public IEnumerable<Book> GetByAuthor(int authorId) { ... }

    // ...
}

Routing to controller actions in ASP.NET Core shows the following:

[Route("[controller]/[action]")]
public class HomeController : Controller
{
    [Route("~/")]
    [Route("/Home")]
    [Route("~/Home/Index")]
    public IActionResult Index()
    {
        return ControllerContext.MyDisplayRouteInfo();
    }

    public IActionResult About()
    {
        return ControllerContext.MyDisplayRouteInfo();
    }
}

In the preceding code, the Index method templates must prepend / or ~/ to the route templates. Route templates applied to an action that begin with / or ~/ don't get combined with route templates applied to the controller.