ASP.NET MVC - Passing Parameters For Default Route Using RouteConstraint

502 Views Asked by At

I am facing an issue having 2 default asp.net mvc routes (applied through custom constraints). What I am trying to do is, load different views based on if the parameters are supplied in the routedictionary or not. Below are my two routes in RouteConfig.cs

        routes.MapRoute(
            name: "DefaultWatch",
            url: "{controller}/{action}/{title}",
            defaults: new { controller = "Watch", action = "Index", title = ""},
            constraints: new { title = new VideoTypeRouteConstraint() }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}",
            defaults: new { controller = "Main", action = "Index"}
        );

I want to open /watch/Index/{title} if the title string is supplied or just open my default route /Main/Index. Below is the implementation for my route constraint.

In VideoTypeRouteConstraint.cs

public class VideoTypeRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (values.ContainsKey(parameterName))
        {
            string value = values[parameterName].ToString();
            return !String.IsNullOrEmpty(value) ? true : false;
        }
        return false;
    }
}

What I am trying to do check if RouteValueDictionary contains the title variable and if so, returns true so my /Watch/Index/{title} is executed.

Now it works when I hit the below urls

http://localhost:53923/    //returns /Main/Index correctly
http://localhost:53923/?title=routing-optional-parameters-in-asp-net-mvc-5  //Also returns /Main/Index because the value in RouteValueDictionary is null but I can see the value in httpContext.Request[parameterName]

http://localhost:53923/routing-optional-parameters-in-asp-net-mvc-5  //this DOES NOT WORK - Returns 404

RouteValueDictionary contains the key (title) but its value is always null. This is where the issue is I believe but I'm not being able to identify it.

The whole idea of this was to clean my urls for SEO which were way longer when I used a separate controller.

0

There are 0 best solutions below