How can I generate constant urls for my ASP.NET MVC actions?

1.2k Views Asked by At

I want to generate constant urls for my actions. Something like this:

public const string ControllerName_ActionName = "/ControllerName/ActionName";

I have tried to use T4MVC but it generates only methods with T4MVC_System_Web_Mvc_ActionResult. Is there any solution without pain?

I want to use them in an external project as a library. The project doesn't know about my MVC application. It can be a simple console application with WebClient.

2

There are 2 best solutions below

0
On BEST ANSWER

I have customized T4MVC template for my issue:

public static class UrlConst {
<#foreach (var controller in DefaultArea.GetControllers()) {
    foreach (var action in controller.ActionMethods.ToList())
    { #>
    public const string <#=controller.Name#>_<#=action.ActionName#> =
        "/<#=controller.Name#>/<#=action.ActionName#>";
  <#}   
} #>
}
3
On

From within the web application

T4MVC also generates a new extension method for Url.Action(). So for instance now you can use something like this:

return Redirect(Url.Action(MVC.Account.Index()));

From an external library

T4MVC only generates constants so you can be certain that when it compiles the routes will be correctly generated runtime. It is not easy to generate a file containing something like url => Controller.Action because this depends on your routing config, url wildcards, ordering, http protocol etc.

If your project has no knowlegde of the MVC application and you want to have a file containing the constant urls it can hit how would this file be generated if your route is the following:

      routes.MapRoute(
          name: "Catch-all content route",
          url: "{*url}",
          defaults: new { controller = "ContentPage", action = "Index" }