Authorize with roles:
You can refactor the roles into constants and consume them like this:
public class StaticRoles
{
public const string A = "A";
public const string B = "B";
public const string C = "C";
public const string ABC = "A, B, C";
}
Use these constants like this:
[Authorize(Roles = StaticRoles.ABC)]
[Route("foo")]
public IActionResult Foo()
Consuming routes in views:
When generating links, you can use tag helpers for links which automatically read the Route attribute from the controller method:
<a asp-controller="@nameof(HomeController).Replace("Controller", string.Empty)" asp-action="@nameof(HomeController.Foo)">Foo</a>
You should refactor .Replace("Controller", string.Empty) into a String extension method to reduce code bloat.
Consuming routes in code:
If you want to have the same functionality as the tag helpers in code, you can use the LinkGenerator class which is automatically injected
Use dependency injection to get the reference to the LinkGenerator
public class HomeController : Controller
{
private readonly LinkGenerator linkGenerator;
public HomeController(LinkGenerator linkGenerator)
{
this.linkGenerator = linkGenerator;
}
// ..
}
Inside HomeController, you can then use
linkGenerator.GetPathByAction(
nameof(HomeController.Index),
nameof(HomeController).Replace("Controller", string.Empty))
};
GetPathByAction has a third parameter when the route has parameters as part of the URL:
linkGenerator.GetPathByAction(
nameof(HomeController.Index),
nameof(HomeController).Replace("Controller", string.Empty),
values: new { version = user.Version})
};