Quantcast
Channel: ASP.NET MVC / Web API / Web Pages
Viewing all articles
Browse latest Browse all 7925

Edited Issue: HttpRouteUrl does not generate a URL for a route with constraints on optional parameters. [602]

$
0
0
1. Create a new ASP.NET MVC 4 project, subtype: Web API.
2. Add the following section to Views/Home/Index.cshtml:

<section class="content-wrapper main-content clear-fix">
<h3>Demonstrating HttpRouteUrl problem:</h3>
<ul>
<li>Route: '@Url.HttpRouteUrl("DefaultApi", null)'</li>
</ul>
</section>

3. Run. The output of the home page will have an extra section displaying: Route: '/api/Home'.

4. Add a number constraint to the DefaultApi route:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
constraints: new { id = @"\d+" },
defaults: new { id = RouteParameter.Optional }
);

5. Run again. The output is now ''.

The newly configured route is no match for the call to HttpRouteUrl unless you add the parameter to the route values that matches the constraint. I added a sample project here: https://github.com/DaveVdE/RouteProblem


Viewing all articles
Browse latest Browse all 7925

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>