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.
EDIT: Complete rewrite:
You should add your custom data to
routeData.Valuesinstead ofrouteData.DataTokens.And registering your
MyRouteroute (MVC uses the first matching route so it should go first):