How to set cookie value as default value for MapRoute parameter? - asp.net-mvc

Introduction:
I develop multilingual web application. Admin can create new languages (this information is stored in database). So languages are not hardcoded somewhere in code. The user's preferred language is stored in browser cookie.
Now i want to configure url routes from this:
www.host.com/home/about
to this:
www.host.com/{lang}/home/about
RouteConfig.cs looks like:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
foreach (Route r in routes)
{
r.Url = "{lang}/" + r.Url;
if (r.Defaults == null)
r.Defaults = new RouteValueDictionary();
r.Defaults.Add("lang", ServiceLocalization.GetLanguageFromBrowserCookie());
}
}
}
Parameter {lang} is added to every request url. I need to set default value from cookie. Service method GetLanguageFromBrowserCookie() uses HttpContext.Current.Request.Cookies object to access cookies sent by the client.
But HttpContext.Current.Request object is not accessible at this stage of request-handling pipeline. And i get this error: "Request is not available in this context"
Is there a way to fetch MapRoute parameter with cookie value?

Ok. I figured out how to do this. We need to create custom RouteHandler to process request url with extra logic.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new CustomRouteHandler();
}
}
public class CustomRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var route = (Route)requestContext.RouteData.Route;
if (!route.Url.Contains("{lang}"))
route.Url = "{lang}/" + route.Url;
if (route.Defaults == null)
{
route.Defaults = new RouteValueDictionary();
route.Defaults.Add("lang", ServiceLocalization.GetLanguageFromBrowserCookie().CodeName);
}
else
{
route.Defaults["lang"] = ServiceLocalization.GetLanguageFromBrowserCookie().CodeName;
}
return base.GetHttpHandler(requestContext);
}
}
I create CustomRouteHandler and pass it to Default route. In GetHttpHandler method we can access current HttpRequest and get any data from request.

Related

.Net Route Action Parameter coming back null despite being in url

UPDATE: It works fine is I add another parameter. I have no idea why.
Not sure what I am doing wrong, this route looks the same as the other routes, I've looked at all the other stackoverflow posts on the subject and everything looks up to snuff. Maybe someone can see something I can't?
Error: action parameter can't be null
The url: http://localhost:1319/EntryHistory/Entry/B2AAAA4A-B174-4C28-924F-A3B2027DD745
EntryHistoryController.cs:
public class EntryHistoryController : Controller
{
public ActionResult Entry(string entryId)
{
Guid parsedEntryId = Guid.Parse(entryId);
var history = new EntryHistoryService().BuildEntryHistoryViewModel(parsedEntryId);
return View(history);
}
}
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
...
EntryHistoryRoutes(routes);
...
}
private static void EntryHistoryRoutes(RouteCollection routes)
{
routes.MapRoute(
"revisionhistory",
"entryhistory/entry/{entryId}",
new
{
controller = "entryhistory",
action = "entry",
entryId = UrlParameter.Optional
}
);
}
add attribute routing
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
...... your routes
//convention-based routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
and action
[Route("~/entryhistory/entry/{entryId}")]
public ActionResult Entry(string entryId)

MVC custom URL routing

I have a route configured like
routes.MapRoute(
name: "Default",
url: "TEST/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
It works fine to redirect to respective controller and actions.
I want to add another redirection on TEST so that if somebody uses www.mysite.com/TEST, it should redirect www.mysite.com/Test/Home instead of giving 403- Forbidden: Access is denied error.
I'm trying like this but could not achieve it.
routes.MapRoute(
name: "AnotherDefault",
url: "TEST",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Basically, what I'm trying to do is to redirect from www.mysite.com or www.mysite.com/TEST to www.mysite.com/TEST/Home
To add to the confusion, I also had a physical folder TEST in my application root. Just wondering if keeping another web.config in there would solve? I tried but of no luck
Please advise what i'm missing here. Thanks
After some experiment I have found that the physical folder TEST is causing redirection rule to fail. I changed my route to TEST1 in URL instead of TEST, it worked. But, I can't rename TEST folder. Please advise
Please set the property RouteExistingFiles to true above the Route configurations
public static void RegisterRoutes(RouteCollection routes)
{
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "TEST/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
This should allow you to keep the name of folder and also the route name to be "TEST". Let me know how it works out for you
Keep using the first route:
routes.MapRoute(
name: "Default",
url: "TEST/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
and add this in your Web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
<handlers>
<remove name="UrlRoutingHandler"/>
</handlers>
</system.webServer>
We Can manage url routing by validate from database.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// here i pass my parameter like wwww.abc.com/country-state-city
routes.MapLocalizedRoute("SeoFriendlyUrl",
"{SeoFriendlyName}",
new { controller = "Company", action = "Index" },
new[] { "MigrationTest.Controllers" });
// it is default
routes.MapRoute( name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public static class LocalizedRouteExtensionMethod
{
public static Route MapLocalizedRoute(this RouteCollection routes, string name, string url, object defaults, string[] namespaces)
{
return MapLocalizedRoute(routes, name, url, defaults, null /* constraints */, namespaces);
}
public static Route MapLocalizedRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
{
if (routes == null)
{
throw new ArgumentNullException("routes");
}
if (url == null)
{
throw new ArgumentNullException("url");
}
var route = new clsRouteData(url, new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints),
DataTokens = new RouteValueDictionary()
};
if ((namespaces != null) && (namespaces.Length > 0))
{
route.DataTokens["Namespaces"] = namespaces;
}
routes.Add(name, route);
return route;
}
}
public class clsRouteData : Route
{
public clsRouteData(string url, IRouteHandler routeHandler)
: base(url, routeHandler)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData data = base.GetRouteData(httpContext);
if (data != null)
{
var SeoFriendliyName = data.Values["SeoFriendlyName"] as string;
if (SeoFriendliyName=="india-raj-jaipur")
{
data.Values["controller"] = "City";
data.Values["action"] = "Index";
// Can be send parameter
//data.Values["Id"] = Resutls.Id;
}
}
else
{
data.Values["controller"] = "Norecord";
data.Values["action"] = "Index";
// Can be send parameter
//data.Values["Id"] = Resutls.Id;
}
return data;
}
}

How to set a Custom url in ASP.net MVC?

I have one web application in ASP.net MVC and I have to set a custom url instead of default url.
Url like : www.hostname.com//IEAdmin/OUser/ViewStep1/a0a765a1-21a5-47d2-8ac5-bcef10baf76c
I need url like www.hostname.com/OUser/a0a765a1-21a5-47d2-8ac5-bcef10baf76c
Is it possilbe ?
Let me know if it is possible then
Which configuration i have to set in Route.config.
You will need to add a couple of additional routes, BEFORE the routes you have already defined:
routes.MapRoute(
name: "Test",
url: "OUser/{id}",
defaults: new { controller = "OUser", action = "ViewStep1", id = UrlParameter.Optional }
);
PS: you need to define this route in your area registration's route
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("MyRoute", "OUser/{id}", new { controller = "MyController", action = "MyAction" }, new { id = UrlParameter.Optional });
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}

How can I get Advanced Url Routing parametres?

It works now like localhost/Controller/Action
but I want it like localhost/MainFolder/SubFolder/Controller/Action
because I need to get my MainFolder and SubFolder name; like
RouteData routeData = htmlHelper.ViewContext.RouteData;
string currentAction = routeData.GetRequiredString("action");
string currentMainFolder = routeData.GetRequiredString("mainFolder");
string currentSubFolder = routeData.GetRequiredString("subFolder");
MyViewEngine Codes;
public class MyViewEngine: RazorViewEngine
{
private static string[] NewViewFormats = new[] { "~/Views/MainFolder/SubFolder/{1}/{0}.cshtml" };
public MyViewEngine()
{
base.ViewLocationFormats = base.ViewLocationFormats.Union(NewViewFormats).ToArray();
}
}
My RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Panel", action = "Index", id = UrlParameter.Optional }
);
ViewEngines.Engines.Add(new MyViewEngine());
}
My Views Folder;
My Controllers Folder;
MVC Routes are not filesystem-based like old-style ASP.NET sites. All the controllers are registered at compile and the route just picks the one with the matching name. Where the controller lives on your filesystem is irrelevant.

Parameter value not passed in ASP.NET MVC route

I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've added the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
The idea is for me to able to navigate to http://localhost:123/home/filter/mynameparam. Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
When I navigate to http://localhost:123/home/filter/mynameparam the contoller method Filter is called, but the parameter name is always null.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name parameter for Filter().
The Default route should be the last one.
Try it this way:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.

Resources