How can I map URLs for a multi-tenanted MVC site? - asp.net-mvc

I have a multi-tenanted MVC site where all the MapRoutes start as follows:
http://foo.com/{organisation}/{branch}/{controller}/{action}
Each organisation can have several branches. For example:
The Metro organisation has two branches:
http://foo.com/metro/north/
http://foo.com/metro/south/
The Gold organisation has three branches:
http://foo.com/gold/usa/
http://foo.com/gold/eu/
http://foo.com/gold/asia/
There are further Controllers and Actions below these but EVERY MapRoute / url follows this format.
My organisations don't like the generic URLs and want to personalize them. Is it possible to change from this:
http://foo.com/metro/north/
http://foo.com/metro/south/
To this (implying that {branch} = 'metro')
http://www.metrowebsite.com/north/
http://www.metrowebsite.com/south/
Using some kind of URL mapping or URL re-direction without changing the MVC website?
I'm not even sure of the correct terminology to use to search for help on this.
Thanks in anticipation!

I guess you could map all the DNS entries for those URLs to point to the same webserver instance and then use a URL rewriting configuration to translate that into the 'standard' path that your application expects.
I have used URL rewrite myself (http://www.iis.net/downloads/microsoft/url-rewrite) to do something similar, so I know in concept it works. I just can't 100% say that it recieves the full url (i.e. http://www.metrowebsite.com/north/) and not just the path (i.e. /north). You may need to verify this part.
Essentially the module would take incoming URls, i.e. http://www.metrowebsite.com/north/
and could use a regular expression to adapt it into the format http://www.metrowebsite.com/north/
Here is an example of one that I did:
<rewrite>
<rules>
<rule name="MyRewriteRul" stopProcessing="true">
<match url="Some/Sort/Of/Friendly/Url/$" />
<action type="Rewrite" url="MyControllerName/MyActionName" appendQueryString="true" />
</rule>
</rewrite>
This configuration goes directly into your Web.config file - see the documentation for more details on this.
Very basic example that rewrites incoming Urls matching 'Some/Sort/Of/Friendly/Url/' and rewrites it into the format my system expects, i.e. 'MyControllerName/MyActionName'.
This is something you could build upon I think.
In regards to your routes, I would recommend modifying them slightly, introducing some 'static' components to the urls so that you don't get unnecessary path match conflicts. I also did a similar multi-tenant pathing exercise.
Consider doing the following:
http://foo.com/o/{organisation}/b/{branch}/{controller}/{action}
You can then have a match rule as such:
routes.MapRoute(
"Organisation.Default",
"o/{organisation}/b/{branch}/{controller}/{action}/{id}",
new { siteView = "Public", controller = "Home", action = "Index", id = "0" });
Which won't conflict with your default routes, as the /o and /b parts clearly signify that its route for an organisation. You can obviously modify this as you like, just something to consider. :)

Related

Umbraco - Dynamic Pages

I was hoping someone might be able to give me some help with what I am planning to do...
I want to create a dynamic "City.aspx" page that accepts a url parameter and dynamically generates a page based on that particular city.
For example, if someone called "City.aspx?city=london" then it would build a page with custom content relating to London and if someone called the page "City.aspx?city=manchester" it would build the page with content relating to Manchester.
I have looked into building the sitemap and UrlRewriting and am pretty sure i can redirect to this new page with a parameter but have no idea what I need to do next.
Can anyone help please?
Thanks
TaxiRoute
I would recommend that you create url's like /city/london/1234 where the last part is the ID of your document.
By using the built-in UrlRewrite function in Umbraco, you can make the url be internally rewritten to /city.aspx?name=london&id=1234
In the /config/Urlewriting.config you can add rewrite rules.
For the above you need something like this:
<add name="city_rewrite"
virtualUrl="^~/city/(.*)/(.*)"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/city.aspx?name=$1&cityid=$2"
ignoreCase="true" />
Once you have this sorted out, you can use the following code in your code-behind off the City.aspx Macro to get the corresponding Document.
// get the city Document Id from the querystring
string cityID = HttpContext.Current.Request.QueryString["cityid"];
if (!string.IsNullOrWhiteSpace(cityId))
{
// get the cityNode
Node cityNode = new Node(cityId);
// do whatever you want with this node, like display it's data
}
This is a .NET Macro, but of course you can do the same with XSLT or Razor-code.
If you have the information outside of standard Umbraco content that is dynamic for each city, then simply write a macro or macros (or partial views?) to get the dynamic data via that "city" get parameter. Then you can use UrlRewriting to make URLs look like standard web pages (/city/london.aspx). UrlRewriting will make that URL appear to the server as though it was this: /city.aspx?city=london. (http://our.umbraco.org/wiki/reference/packaging/package-actions/community-made-package-actions/add-an-url-rewrite-rule)
In your macros you can either pass the "city" get parameter to the macro(s) as a macro parameter via bracket syntax (http://our.umbraco.org/wiki/reference/templates/umbracomacro-element/macro-parameters/advanced-macro-parameter-syntax). Or your can just get the city parameter via request variables (razor) or Umbraco.library (XSLT).

Prevent static file handler from intercepting filename-like URL

In my web application I have a route which looks like this:
routeCollection.MapRoute(
"AdfsMetadata", // name
"FederationMetadata/2007-06/FederationMetadata.xml", // url
new { controller = "AdfsController", action = "MetaData" }); // defaults
The idea behind this route was to work better with Microsoft AD FS server (2.0+) which looks for AD FS metadata at this point when you just specify a host name. With MVC3 all worked fine. But we upgraded the project to MVC4 recently and now the call for this URL results in a 404, the handler mentioned on the error page is StaticFile and the physical path is D:\path\to\my\project\FederationMetadata\2007-06\FederationMetadata.xml. I assume that MVC or ASP.NET "thinks" it must be a request for a static file and looks for the file, but it isn't a file. The data is generated dynamically - that's why I routed the URL to a controller action. The problem is that even the Route Debugger by Phil Haack doesn't work. It's just a 404 with no further information besides that IIS tried to access a physical file which isn't there.
Does anyone have a solution for this? I just want this URL to be routed to a controller action.
P.S.: I'm not 100% sure that the cause was the upgrade to MVC4, it was just a guess because the error occurred at about the same time as the upgrade, and the same route works in another project which is still using MVC3.
Edit:
I have a custom ControllerFactory which needs the full class name (AdfsController instead of Adfs), so the suffix Controller is correct in this case.
Add the following to the <handlers> section of the <system.webServer> node:
<add
name="AdfsMetadata"
path="/FederationMetadata/2007-06/FederationMetadata.xml"
verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
This instructs IIS that GET requests to the specified url should be handled by the managed pipeline and not considered as static files and served by IIS directly.
I have a custom ControllerFactory which needs the full class name
(AdfsController instead of Adfs), so the suffix Controller is correct
in this case.
Double check this please. Try with and without the Controller suffix in the route definition.
IIS by default is serving that file as static withouth going into ASP pipeline, can you change the route to not have a .xml extension (which is not necessary at least you have a specific requirement about that)
You can specifiy the route like this:
routeCollection.MapRoute(
"AdfsMetadata", // name
"FederationMetadata/2007-06/FederationMetadata", // url
new { controller = "AdfsController", action = "MetaData" }); // defaults
Other solution would be to add to your web.config
<modules runAllManagedModulesForAllRequests="true">
but I recommend you to avoid this as possible since what it does is to stop IIS from serving all static files
EDIT Last try... a custom http handler for that specific path would work. This post is similar to your problem only that with images (look for "Better: Custom HttpHandlers" section)

How can I custom encode/decode route values?

I have this route:
{controller}/{id}/{action}
Because I think it makes more sense from RESTful perspective.
The problem is that id can contain slashes (/) and those are treated as route separators even when encoded as "%2F". Even when I have this Web.config section in place:
<uri>
<schemeSettings>
<add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
<add name="https" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
</schemeSettings>
</uri>
Because I have id in the middle I can't employ {*id} approach which captures the rest of the route including the action.
It looks like my only option is to encode / into an RFC compliant character like !, however I do not want to do it using ad-hoc custom code inside controller. I want controller to receive id intact, already decoded. And I want my Url.Action to generate properly encoded URL. Is that too much to ask from MVC, or do I need to scatter ActionFilters and custom URL helpers around?
The only way I could find is to throw in a custom IRouteConstraint to manipulate the RouteValueDictionary it receives. That sounds like a dirty hack though: a constraint manipulating its input. God knows its side effects. Do you think this is a sane enough idea, or is there a better mechanism in ASP.NET MVC allowing that?
EDIT: This workaround only works when parsing the route, not when generating one.
What you are trying to do cannot be done; this has been answered several times on SO - especially of late in relation to RavenDb which uses "/" in the Id field by default (though this can be changed)

How do I instruct Grails to always create URL:s that ends with slash (/)?

Consider the following Grails URL mapping:
class UrlMappings {
static mappings = {
"/something/${foo_id}/" {
controller = "foo"
action = "bar"
}
}
When generating URL:s using g:link ..
<g:link controller="foo" action="bar" params="[foo_id: 123]">foobar</g:link>
.. the resulting link looks like ..
foobar
Note that the ending slash in the URL mapping is removed.
However, both the URL:s /something/123 and /something/123/ still work.
Due to the requirements of the application I'm building I must make "ends with slash"-version of the URL the primary one. Ideally I'd like to make the URL not ending with slash return a 404 (to avoid canonical page issues).
What is the best and most general way to make Grails create URL:s where ending slashes are not removed as described above?
One way to solve it would be to create all URL:s manually, but I do not want to go that way.
Unfortunately grails URL mapping mechanism is not that sophisticated. So while forward URL mapping will work well (that is from URL to the controller) the reverse must be done manually to achive the described outcome.
Probably the best approach would be to create your own tag to output the desired links.
If you are looking for a way to create a groovy tag, that always add slash(/) add the end of the url, your best bet is to create a grails custom tagLib which create links, like the way g:link do.
But I don't know if that stops navigating by the link with out the slash.

ASP.NET MVC, Url Routing: Maximum Path (URL) Length

The Scenario
I have an application where we took the good old query string URL structure:
?x=1&y=2&z=3&a=4&b=5&c=6
and changed it into a path structure:
/x/1/y/2/z/3/a/4/b/5/c/6
We're using ASP.NET MVC and (naturally) ASP.NET routing.
The Problem
The problem is that our parameters are dynamic, and there is (theoretically) no limit to the amount of parameters that we need to accommodate for.
This is all fine until we got hit by the following train:
HTTP Error 400.0 - Bad Request
ASP.NET detected invalid characters in the URL.
IIS would throw this error when our URL got past a certain length.
The Nitty Gritty
Here's what we found out:
This is not an IIS problem
IIS does have a max path length limit, but the above error is not this.
Learn dot iis dot net
How to Use Request Filtering
Section "Filter Based on Request Limits"
If the path was too long for IIS, it would throw a 404.14, not a 400.0.
Besides, the IIS max path (and query) length are configurable:
<requestLimits
maxAllowedContentLength="30000000"
maxUrl="260"
maxQueryString="25"
/>
This is an ASP.NET Problem
After some poking around:
IIS Forums
Thread: ASP.NET 2.0 maximum URL length?
http://forums.iis.net/t/1105360.aspx
it turns out that this is an ASP.NET (well, .NET really) problem.
The heart of the matter is that, as far as I can tell, ASP.NET cannot handle paths longer than 260 characters.
The nail in the coffin in that this is confirmed by Phil the Haack himself:
Stack Overflow
ASP.NET url MAX_PATH limit
Question ID 265251
The Question
So what's the question?
The question is, how big of a limitation is this?
For my app, it's a deal killer. For most apps, it's probably a non-issue.
What about disclosure? No where where ASP.NET Routing is mentioned have I ever heard a peep about this limitation. The fact that ASP.NET MVC uses ASP.NET routing makes the impact of this even bigger.
What do you think?
I ended up using the following in the web.config to solve this problem using Mvc2 and .Net Framework 4.0
<httpRuntime maxUrlLength="1000" relaxedUrlToFileSystemMapping="true" />
Http.sys service is coded with default maximum of 260 characters per Url segment.
An "Url segment" in this context is the content between "/" characters in the Url. For example:
http://www.example.com/segment-one/segment-two/segment-three
The max allowed Url segment length can be changed with registry settings:
Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters
Value: UrlSegmentMaxLength
Type: REG_DWORD
Data: (Your desired new Url segment maximum allowed length, e.g. 4096)
More about http.sys settings:
http://support.microsoft.com/kb/820129
The maximum allowed value is 32766. If a larger value is specified, it will be ignored. (Credit: Juan Mendes)
Restarting the PC is required to make a change to this setting take effect. (Credit: David Rettenbacher, Juan Mendes)
To solve this, do this:
In the root web.config for your project, under the system.web node:
<system.web>
<httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
...
In addition, I had to add this under the system.webServer node or I got a security error for my long query strings:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxUrl="10999" maxQueryString="2097151" />
</requestFiltering>
</security>
...
OK so part of the reason I posted this was also because we have found a work around.
I hope this will be useful to someone in the future :D
The workaround
The workaround is quite simple, and it's quite nice too.
Since we know which parts of the site will need to use dynamic parameters (and hence will have a dynamic path and length), we can avoid sending this long url to ASP.NET routing by intercepting it before it even hits ASP.NET
Enter IIS7 Url Rewriting (or any equivalent rewrite module).
We set up a rule like this:
<rewrite>
<rules>
<rule>
<rule name="Remove Category Request Parameters From Url">
<match url="^category/(\d+)/{0,1}(.*)$" />
<action type="Rewrite" url="category/{R:1}" />
</rule>
</rules>
</rewrite>
Basically, what we're doing is just keeping enough of the path to be able to call the correct route downstream. The rest of the URL path we are hacking off.
Where does the rest of the URL go?
Well, when a rewrite rule is fired, the IIS7 URL Rewrite module automagically sets this header in the request:
HTTP_X_ORIGINAL_URL
Downstream, in the part of the app that parses the dynamic path, instead of looking at the path:
HttpContext.Request.Url.PathAndQuery
we look at that header instead:
HttpContext.Request.ServerVariables["HTTP_X_ORIGINAL_URL"]
Problem solved... almost!
The Snags
Accessing the Header
In case you need to know, to access the IIS7 Rewrite Module header, you can do so in two ways:
HttpContext.Request.ServerVariables["HTTP_X_ORIGINAL_URL"]
or
HttpContext.Request.Headers["X-ORIGINAL-URL"]
Fixing Relative Paths
What you will also notice is that, with the above setup, all relative paths break (URLs that were defined with a "~").
This includes URLs defined with the ASP.NET MVC HtmlHelper and UrlHelper methods (like Url.Route("Bla")).
This is where access to the ASP.NET MVC code is awesome.
In the System.Web.Mvc.PathHelper.GenerateClientUrlInternal() method, there is a check being made to see if the same URL Rewrite module header exists (see above):
// we only want to manipulate the path if URL rewriting is active, else we risk breaking the generated URL
NameValueCollection serverVars = httpContext.Request.ServerVariables;
bool urlRewriterIsEnabled = (serverVars != null && serverVars[_urlRewriterServerVar] != null);
if (!urlRewriterIsEnabled) {
return contentPath;
}
If it does, some work is done to preserve the originating URL.
In our case, since we are not using URL rewriting in the "normal" way, we want to short circuit this process.
We want to pretend like no URL rewriting happened, since we don't want relative paths to be considered in the context of the original URL.
The simplest hack that I could think of was to remove that server variable completely, so ASP.NET MVC would not find it:
protected void Application_BeginRequest()
{
string iis7UrlRewriteServerVariable = "HTTP_X_ORIGINAL_URL";
string headerValue = Request.ServerVariables[iis7UrlRewriteServerVariable];
if (String.IsNullOrEmpty(headerValue) == false)
{
Request.ServerVariables.Remove(iis7UrlRewriteServerVariable);
Context.Items.Add(iis7UrlRewriteServerVariable, headerValue);
}
}
(Note that, in the above method, I'm removing the header from Request.ServerVariables but still retaining it, stashing it in Context.Items. The reason for this is that I need access to the header value later on in the request pipe.)
Hope this helps!
I was having a similar max URL length issue using ASP.NET Web API 4, which generated a slightly different error:
404 Error
The fix for me was described above by updating the Web.config with BOTH of the following tags:
<system.web>
<httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
and
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxUrl="10999" maxQueryString="2097151" />
</requestFiltering>
</security>
I think you're trying to hard to use GET. Try changing the request method to POST and put those query string parameters into the request body.
Long URL does not help SEO as well, does it?
It appears that the hard-coded max URL length has been fixed in .NET 4.0. In particular, there is now a web.config section with:
<httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048" />
that let you expand the range of allowed URLs.

Resources