Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Controller Route in ASP.NET Core

So I have a HomeController, to access it along with Actions I have to type url.com/home/action.

Would it be possible to change this to something else like url.com/anothernamethatpointstohomeactually/action?

like image 623
meds Avatar asked Aug 21 '17 22:08

meds


People also ask

How do I enable routing in .NET Core?

Inside the ConfigureRoute method, you can configure your routes; you can see that this method has to take a parameter of type IRouteBuilder. The goal of routing is to describe the rules that ASP.NET Core MVC will use to process an HTTP request and find a controller that can respond to that request.

What is UseEndpoints in ASP.NET Core?

UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint.

How do I specify a route in Web API?

As the name implies, attribute routing uses [Route()] attribute to define routes. The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config. MapHttpAttributeRoutes() method.


2 Answers

I suggest you to use attribute routing, but of course it depends on your scenario.

[Route("prefix")]
public class Home : Controller {

    [HttpGet("name")]
    public IActionResult Index() {
    }

}

This will be found at url.com/prefix/name

There are a lot of options to attribute routing, some samples:

[Route("[controller]")] // there are placeholders for common patterns 
                           as [area], [controller], [action], etc.

[HttpGet("")] // empty is valid. url.com/prefix

[Route("")] // empty is valid. url.com/

[HttpGet("/otherprefix/name")] // starting with / won't use the route prefix

[HttpGet("name/{id}")]
public IActionResult Index(int id){ ... // id will bind from route param.

[HttpGet("{id:int:required}")] // you can add some simple matching rules too.

Check Attribute Routing official docs

like image 169
Bart Calixto Avatar answered Sep 30 '22 20:09

Bart Calixto


Using the Route attribute on top of your controller will allow you to define the route on the entire controller. [Route("anothernamethatpointstohomeactually")]

You can read more here.

like image 33
ザヘド Avatar answered Sep 30 '22 18:09

ザヘド