I have a webservice project that is being expanded to host multiple APIs instead of just one, so I wanted to cleanup the routes without breaking the old version. The main API used to sit off of a controller named API and accept parameters like this:
api/{language}/{action}/{*parameters}
Now, I have an Area named API that is going to house each of the APIs in their own controller and the route will look like this:
api/{controller}/{language}/{action}
I still need the old route to be usable for legacy apps already using the old route, I was hoping just to be able to create a 2nd "legacy" route that would catch the old pathing and use the new controller. I tried this but it only worked then with the new location and the ikd one returned a 404.
api/{language}/{action}/{*parameters}",
new { controller = "api1", action = "Index", language = "json" }
Any ideas on how to accomplish this? I tried RouteMagic but it didn't seem to work. Maybe I set the redirect up wrong though.
Ok, figured out after getting a sandwhich...just needed to add route constraints so that the old version would not catch on the new route format:
routes.MapRoute(
"API_default",
"api/{controller}/{language}/{action}",
new { controller = "api1", action = "Index", language = "json" },
new { language = "json|xml" }
);
routes.MapRoute(
"API_legacy",
"api/{language}/{action}/{*parameters}",
new { controller = "api1", action = "Index", language = "json", parameters = UrlParameter.Optional },
new { language = "json|xml" }
);
Related
I need to provide language specific routes for my Asp.Net MVC application. The language should be part of the Url Path (http://myapp/en/Blog) and when it is ommitted the default language have to be used.
http://myapp/en/Blog -> Blog in the English version
http://myapp/Blog -> Blog in the Default (portuguese) Language version
To address this issue I created two Routes bellow:
routes.MapRoute(
name: "Default.lang",
url: "{lang}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { lang = #"^[a-zA-Z]{2}$" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The routes are working as expected but I'm getting weird results when I try to use the Url.RouteUrl method to get alternative language urls.
Example 1 - Path: /
url.Action("Index", "Blog") // returns "/Blog" that is OK
url.Action("Index", "Blog", new { lang = "en" }); // returns "/en/Blog" that is also OK
Example 2 - Path: /en
url.Action("Index", "Home") // returns "/en/Blog" (??????????) Not OK
url.Action("Index", "Home", new { lang = "en" }); // returns "/en/Blog" that is OK
As you can see I get a wrong result when I access the url http://myappurl/en and try to use the Url.Action method without pass any route value (same result with Url.RouteUrl)
Does anyone knows what is wrong with my routes?
[EDIT] I'm not sure if the issue is related to the route because I've tested the routes using "en" as first route's constraint and I got the same result.
After some digging inside System.Web.Mvc and System.Web.Routing source code I found that this behavior is expected. I presume that it is designed to correctly work in applications running inside Virtual Directories.
This can be confirmed in this answer that I found when was researching if someone else had the same problem with virtual path and route resolution.
Workaround
Use named route resolution with Url.RouteUrl method that has and different implementation and works as expected.
Example:
var blogDefaultUrl = url.RouteUrl("Default", new {action = "Index", controller = "Blog"});
var blogLangageSpecifictUrl = url.RouteUrl("Default.lang", new { action = "Index", controller = "Blog", lang = language });
I was avoiding to use named routes because my application design is a little bit more complicated than I demonstrated above. By this reason I have to discover at run time the route that matches the Request.Url and from that point I call the RouteUrl to get the alternative languages url to the content.
I'm working on a ASP.NET Core website (previously named ASP.NET 5 / vNext) with Angular. In order for Angular to work I need to have a catch-all route:
app.UseStaticFiles();
app.UseMvc(routes =>
{
// Angular fallback route
routes.MapRoute("angular", "{*url}", new { controller = "Home", action = "Index" });
});
I also have a few files/folders in wwwroot, like:
wwwroot/app
wwwroot/assets
wwwroot/lib
When any requests are made to these paths, for example http://example.com/assets/css/test.css, and the file (test.css) does NOT exist, it should not continue to the fallback route. It should return a 404.
Right now, if the file does not exist it returns the Angular HTML. So, how can I tell it that any path that starts with '/assets' should only be routed / served by UseStaticFiles?
This seems to work:
app.MapWhen(
context => {
var path = context.Request.Path.Value.ToLower();
return
path.StartsWith("/assets") ||
path.StartsWith("/lib") ||
path.StartsWith("/app");
},
config => config.UseStaticFiles());
However, I'm not sure if there are any performance (or other type of) implications. I'll update if I come across any.
It is strange that this common case (since many use SPA) is not covered almost anywhere and everyone has to invent something. I have found that the best way to do that is to add constraint (e.g. do not use the route if there is /api or "." in the path). Unfortunately this is not supported out of the box, but you can write this constraint yourself or copy the one I wrote from here.
There are a bit more details in this post. But generally the code looks like this:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller}/{action}");
routes.MapRoute(
name: "angular",
template: "{*url}",
defaults: new {controller = "Home", action = "Index"},
constraints: new {url = new DoesNotContainConstraint(".", "api/") });
});
P.S. Perhaps this constraint exist out of the box now, but I have not found one. Alternatively a RegEx can be used, but simple one should be way faster.
If you are using attribute template routing then you can apply this elegant solution:
[HttpGet("")]
[HttpGet("{*route:regex(^(?!skipped).*$)}")]
public async Task<IActionResult> Default(string route) { throw new NotImplementedException(); }
So all routes started with skipped will be ignored by this action.
If you want multiple prefixes or anything else then just update regex for your needs.
First Get attribute is needed to handle root of site (in this case route variable is null).
I am trying to get a route like:
{lang:optional}/{controller}/{action}/{id:optional}
With "controller constraints" idea from this article: (MVC Routing Constraint on Controller Names), the above route works very well, when {lang} value is presented or not.
However I have a problem to match this route:
routeName: testRoute
url: {lang:optional}/list/{something:optional}
{controller = "product", action = "index"}
for the above route, the {lang} value must be presented, otherwise it does not work.
I have two workarounds to work it out.
The first way is to set two routes for the above:
The very standard one:
routeName: testRoute
url: /list/{something}
{controller = "product", action = "index"}
and another very standard one:
routeName: testRouteLang
url: {lang:not_optional}/list/{something:optional}
{controller = "product", action = "index", lang="de"}
I am wondering if there is a way to combine the two standard routes into one single route.
The second workaround is to use subdomain name, such as
http://example.com/list (default to English)
http://de.example.com/list (de)
But I really do not like the subdomain idea for the SEO reasons (maybe I am wrong on this point).
My goal is to remove the default "en-us" in the URL. I like this
http://www.example.com/list/something (default as English)
I do not want to force "en-us" in the url
http://www.example.com/en-us/list/something
The "lang" should only be presented in the Url if the current culture is not English:
http://www.example.com/de
http://www.example.com/fr/list/something
Thanks.
Finally I found an very easy and DRY solution. The core thing is to use the HttpContext.Current.RewritePath to inject the default "en", while this "en" will not be shown in the URL.
protected void Application_BeginRequest()
{
var rawUrl = HttpContext.Current.Request.RawUrl;
var segments = HttpContext.Current.Request.Url.Segments;
var segment1 = segments.Count() >= 2 ? segments[1] : string.Empty;
if (IsSomethingThatIWantToHandle("are,you,js,script,css,jpg,png,and,so,on?")
&& !LittleHelper.DoIHaveValidLangAlready(segment1))
{
HttpContext.Current.RewritePath("/en" + rawUrl);
}
}
When generate URL, if lang is null/empty, the URL will be have a double //. I just need a little helper to remove the extra "/".
When define a route, a trick is that the area name must be added to the DataTokens, otherwise the view cannot be correctly located, if areas are presented in the project.
routes.MapRoute(
"good name",
"{lang}/some-cool-stuff/{id}/{slug}",
defaults: new { area = "bigarea", controller = "bigcontroller", action = "tinyaction",
lang = UrlParameter.Optional, id = UrlParameter.Optional, slug = UrlParameter.Optional }
, constraints: new { lang = new CultureConstraint() }
).DataTokens.Add("area", "bigarea");
The CultureConstraint is very straightforward -- just verify whether it is a valid culture name. The namespace constraints is not necessary. However if the route table is big and complicated then the controller constraints, or even action constraints is very necessary otherwise duplicated routes will be an issue.
My default route in my project now is:
url: "{lang}/{area}/{controller}/{action}/{id}/{slug}",
and it works beautifully as I want.
It would be great if someone could help me on this problem as I am new to web development and ASP.NET MVC. My goal is to design an MVC application which could help users to create their own mini websites. Each user will get their own mini websites and an admin panel to change the pages and template of their sites. I think there are scripts out there to achieve something similar, but we need to create our own for our specific requirements
Towards that goal I created a main mvc 3 application and I created an area as Site under it. We want the user to have their own sub domain urls like www.site1.mainsite.com where site1 is the name of the mini site of the user. For that I added 2 routes one for the main site and another for the area like
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MainSite.UI.Controllers" }
);
In Area Registration
context.MapRoute(
"Sites_default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {controller = new SiteConstraint()},
new[] { "MainSite.UI.Areas.Site.Controllers" });
Both of them have the same url type, but area route have a constraint where I added like
var url = httpContext.Request.Headers["HOST"];
var storeName = url.Split('.')[1];
var match = storeName != "mainsite";
return match;
so far its working, But i dont think its a good design. Now apart from this I need to add 2 more areas one is siteadmin and another is blog.
What should be best way to achieve this?
sub domain urls should be directed to area "site"
subdomain url/Admin should be routed to area "siteadmin"
domain/blog should be routed to blog area.
domain other urls should be handled by main controllers
Thanks in advance
I didnt get even one reply :( But I tried playing with the routes and achieved some what near to what I was looking for.
Thanks to Route Debugger, It helped me to see what was going wrong with the routes
When I tried adding another area "Admin", and registered it with the route below
context.MapRoute(
"SiteAdmin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional },
new { controller = new SiteConstraint() },
new[] { "MainSite.UI.Areas.SiteAdmin.Controllers" }
);
Things started going wrong. Route Debugger helped to me to figure out, what was happening.
For me the order of the Routes really mattered, so I had to make sure that my areas were registered in the correct order.
AreaRegistration.RegisterAllAreas()
was not registering my routes in the correct order, Googling gave me this helper method.
public static class RouteHelper
{
public static void RegisterArea<T>(RouteCollection routes, object state) where T : AreaRegistration
{
var registration = (AreaRegistration)Activator.CreateInstance(typeof(T));
var context = new AreaRegistrationContext(registration.AreaName, routes, state);
var tNamespace = registration.GetType().Namespace;
if (tNamespace != null)
{
context.Namespaces.Add(tNamespace + ".*");
}
registration.RegisterArea(context);
}
}
That method helped me to register the areas in the required order in the Global asax as
RouteHelper.RegisterArea<SiteAdminAreaRegistration>(RouteTable.Routes, null);
RouteHelper.RegisterArea<SiteAreaRegistration>(RouteTable.Routes, null);
I am writing it down, what I got so far as an answer so that someone else may be find it useful.
I am having a lot of trouble using routing infrastructure of asp.net mvc2. I have following routes registered in my global.asax file
routes.MapRoute(
"strict",
"{controller}.mvc/{docid}/{action}/{id}",
new { action = "Index", id = "", docid = "" },
new { docid = #"\d+"}
);
routes.MapRoute(
"default",
"{controller}.mvc/{action}/{id}",
new { action = "Index", id = "" },
new { docConstraint = new DocumentConstraint() }
);
The problem is with first route ("strict"). Three kind of urls can match first route. mycontroller/23/myaction, mycontroller/23/myaction/12 or mycontroller/23/mvaction/stringid. If I try to use this route without specifying value of id everything works fine for example:
Html.ActionLink("Link text", "ActionName", new{docid = 23});
Everything goes well, but if I use links like:
Html.ActionLink("Link text", "ActionName", new{docid = 23, id = 223})
This will produce url currentcontroller.mvc/23/ActionName/223 that is absolutely correct but when it loads the page it gives a JavaScript error in jquery1.4.2.min.js file.
This is strange: if I change id to someid =223 it will reflect in query string and there will be no JS error.
Edit: I have done some further debugging and found when both id and docid are mentioned in route values one thing is ignored in global.asax that is the ignore path.
routes.RouteExistingFiles = false;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.ignoreRoute is totally bypassed and I can see names of JS files in route value dictionary while debugging in my controller.
it gives javascript error in
jquery1.4.2.min.js file
The most likely cause for this is that something you are displaying on the page is different and you are performing an action that is causing the error. Can you supply enough of a sample from the rendered page to show what you are using jQuery for?
If we drag scripts from solution explorer to site.master it results in following output
<script type="text/javscript" src="../../scripts/jquery.min.js"></script>
The leading dots (..) are creating the problem. Putting source path in url.content or using /scripts instead of ../../scripts will solve the problem because these leading periods are forcing them to match some route in global.asax.