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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With