Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Route Default values

i defined two routes in global.asax like below

context.MapRoute("HomeRedirect", "",
                            new
                            {
                                controller = "Home",
                                action = "redirect"
                            });

context.MapRoute("UrlResolver", "{culture}/some",
                            new
                            {
                                culture = "en-gb",
                                controller = "someController",
                                action = "someAction"
                            },
                            new
                            {
                                culture = new CultureRouteConstraint()
                            });

according to above definition, when user request mysite.com/ redirect action of HomeController should be called and in that:

public class HomeController : Controller
{
    public ActionResult Redirect()
    {
        return RedirectToRoute("UrlResolver");
    }
}

i want to redirect user to second defined route on above, so also i specified default values for that and some Constraint for each of those. but when RedirectToRoute("UrlResolver") turns, no default values passed to routeConstraints on second route and No route in the route table matches the supplied values shows.

update

my CultureRouteConstraint:

public class CultureRouteConstraint : IRouteConstraint
{
    bool IRouteConstraint.Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        try
        {
            var parameter = values[parameterName] as string;
            return (someCondition(parameter));
        }
        catch
        {
            return false;
        }
    }
}

now values parameter haven't culture key/value, but route parameter have that.

like image 690
Sadegh Avatar asked Jun 16 '26 18:06

Sadegh


2 Answers

The actual route specified for your second rule is "{culture}/some", so your redirect would have to be, for example, to "/EN-us/some" rather than to the name of the rule.

like image 180
GalacticCowboy Avatar answered Jun 22 '26 03:06

GalacticCowboy


The implementation of HomeController.Redirect() doesn't seem to add any additional value, so why include the route named "HomeRedirect" at all?

How about just deleting it and letting your route named "UrlResolver" handle the requests. You can configure the defaults as you like.

You might add a "catch all" route below the "UrlResolver" route to catch cases where the CultureRouteConstraint() doesn't match the given URL.

like image 35
a7drew Avatar answered Jun 22 '26 02:06

a7drew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!