Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute routing not working in MVC4

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

localhost:33333/test-temp-test-tempparam2

This gives me 404 error. Here in the url, here {testParam2} is having two words test tempparam2 formatted to test-tempparam2. When test word is at last position of {testParam2}, it runs good. That means if the url is like .../test-temp-tempParam2-test runs good. But following give error. .../test-temp-test-tempParam2.

Below is the code that may help...

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

Now try following two url.

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

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

In my case second gives error. In this case first parameter is formatted to test-temp from test temp. First runs good.

How to solve this problem?

like image 473
DhavalR Avatar asked Oct 18 '22 18:10

DhavalR


1 Answers

OP indicated that the last parameter in the route template is an int

Use a route constraint.

Route constraints let you restrict how the parameters in the route template are matched. The general syntax is {parameter:constraint}. For example:

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

Thus, when trying following two URLs.

localhost:(port)/test-temp-1

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

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

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

like image 106
Nkosi Avatar answered Nov 11 '22 15:11

Nkosi