0

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

3 Answers 3

1

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

[HttpGet("/api/whatevernameilike")]
Sign up to request clarification or add additional context in comments.

2 Comments

This solution is Not Working
I am using version 3.1. [HttpGet("/api/..")] and [HttpGet("~/api/..")] both works.
1

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.

Comments

0

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

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

1 Comment

but, that is creating the route as controllername/api/mychosenname

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.