Jaggu
Jaggu

Reputation: 6428

Custom routing asp.net mvc 3 issue

I want that in my action method, my Request.Url.Host should be available. However I don't want to set it in routedata because it will be visible to the user in the url. How can I accomplish this such that Request.Url.Host is available in my domain name variabele but now shown to the user in url? I tried adding it to Request.Form.Add("domain",Request.Url.Host) but it doesn't work because Request.Form is readonly collection.

eg:

public ActionResult Foo(string domain, int id) //id is the standard routedata that you get from url.
{
    ..//code
}

What is the best I can do? I don't want to do Request.Url.Host in every action method so I am trying this approach.

I tried to do this:

public class MyRoute : Route
    {
        #region '----- Method(s) -----'
        public MyRoute(string url, object defaults)
            : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
        { }

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData routeData = base.GetRouteData(httpContext);

            string domain = httpContext.Request.Url.Host;

            routeData.DataTokens["domain"] = domain;

            return routeData;
        }
        #endregion
    }

But my domain variable in my action method comes null.

Thanks.

Upvotes: 2

Views: 1249

Answers (1)

nemesv
nemesv

Reputation: 139758

EDIT: Complete rewrite:

You should add your custom data to routeData.Values instead of routeData.DataTokens.

public class MyRoute : Route
{
    #region '----- Method(s) -----'
    public MyRoute(string url, object defaults)
        : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
    { }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        RouteData routeData = base.GetRouteData(httpContext);

        string domain = httpContext.Request.Url.Host;

        routeData.Values["domain"] = domain;

        return routeData;
    }
    #endregion
}

And registering your MyRoute route (MVC uses the first matching route so it should go first):

routes.Add(new MyRoute("{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }));

Upvotes: 1

Related Questions