3

Currently, I am using strings to define and consume routes, roles, policies, etc. It is easy to misspell or get the string values wrong, as they are not part of the IDE auto-completion and type checking.

Is there a way to utilize some kind of references or symbols in ASP.NET Core 3.1? Maybe through configuration providers and DI?

What I would like to see is to define these string configuration values once somewhere, and then reference them in various parts of the application?

2 Answers 2

2

Why not use constants classes?

public static class RoutingConstants
{
  public const string Route1 = "route1";
  ...
}

And the same thing for any other need

You could then access the constant everywhere like this RoutingConstants.Route1

Sign up to request clarification or add additional context in comments.

1 Comment

That is a possible solution. I am curious if there are also other specialized solutions for configuration, maybe with configuration providers and DI?
0

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})
};

1 Comment

@geeko: Was my answer useful for you?

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.