Attribute routing does not work in MVC4

I am using Attribute Routing in an MVC4 application. I set the route [Route("test-{testParam1}-{testParam2}")] . Here, `{testParam2} 'may consist of the word test. For example, if I enter the URL as shown below,

 localhost:33333/test-temp-test-tempparam2 

This gives me error 404. Here, in the url, here {testParam2} has two words test tempparam2 , formatted to test-tempparam2 . When the word test is in the last position {testParam2} , it works well. This means that if the URL looks like .../test-temp-tempParam2-test , it works well. But after that give an error. .../test-temp-test-tempParam2 .

Below is the code that might help ...

 [Route ("test-{testParam1}-{testParam2}")] public ActionResult Foo (int testParam2) {...} 

Now try to execute two urls.

  • localhost:(port)/test-temp-1

  • localhost:(port)/test-test-temp-1

In my case, the second gives an error. In this case, the first parameter is formatted to test-temp from test temp . It works well at first.

How to solve this problem?

+5
source share
2 answers

The OP pointed out that the last parameter in the route pattern is int

Use route restriction.

Route restrictions allow you to restrict the correspondence of parameters in the route template. The general syntax is {parameter:constraint} . For instance:

 [Route ("test-{testParam1}-{testParam2:int}")] public ActionResult Foo (int testParam2) {...} 

Thus, when you try to execute two URLs.

 localhost:(port)/test-temp-1 localhost:(port)/test-test-temp-1 

The first will match the route data {testParam1 = temp}-{testParam2 = 1}

And the second will match the route data {testParam1 = test-temp}-{testParam2 = 1}

+2
source

Do you have the following code snippet in the Global.asax file?

 public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } 
0
source

Source: https://habr.com/ru/post/1263039/


All Articles