Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override controller name in ASP.NET Core

Similar to this question, but for the new ASP.NET Core.

I can override an action's routing name:

[ActionName("Bar")]
public IActionResult Foo() {

Can I do that for a controller, using attribute routing?

[?("HelloController")]
public SomeController : Controller {

It should allow generation of links using tag helpers:

<a asp-controller="some" ...      // before
<a asp-controller="hello" ...     // after
like image 825
grokky Avatar asked Feb 20 '17 18:02

grokky


People also ask

What is difference between attribute and conventional routing?

Conventional routing: The route is determined based on conventions that are defined in route templates that, at runtime, will map requests to controllers and actions (methods). Attribute-based routing: The route is determined based on attributes that you set on your controllers and methods.

What are controllers in ASP.NET Core?

The controller takes the result of the model's processing (if any) and returns either the proper view and its associated view data or the result of the API call. Learn more at Overview of ASP.NET Core MVC and Get started with ASP.NET Core MVC and Visual Studio. The controller is a UI-level abstraction.

What is route controller?

Routing controllers allow you to create the controller classes with methods used to handle the requests. Now, we will understand the routing controllers through an example. Step 1: First, we need to create a controller. We already created the controller named as 'PostController' in the previous topic.


1 Answers

Such an attribute does not exist. But you can create one yourself:

[AttributeUsage(AttributeTargets.Class)]
public class ControllerNameAttribute : Attribute
{
    public string Name { get; }

    public ControllerNameAttribute(string name)
    {
        Name = name;
    }
}

Apply it on your controller:

[ControllerName("Test")]
public class HomeController : Controller
{
}

Then create a custom controller convention:

public class ControllerNameAttributeConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        var controllerNameAttribute = controller.Attributes.OfType<ControllerNameAttribute>().SingleOrDefault();
        if (controllerNameAttribute != null)
        {
            controller.ControllerName = controllerNameAttribute.Name;
        }
    }
}

And add it to MVC conventions in Startup.cs:

services.AddMvc(mvc =>
{
    mvc.Conventions.Add(new ControllerNameAttributeConvention());
});

Now HomeController Index action will respond at /Test/Index. Razor tag helper attributes can be set as you wanted.

Only downside is that at least ReSharper gets a bit broken in Razor. It is not aware of the convention so it thinks the asp-controller attribute is wrong.

like image 127
juunas Avatar answered Oct 10 '22 07:10

juunas