ASP.Net IgnoreRoutes Does not work - asp.net

I have an svg file as my assets and in routeconfig, I have mentioned the below code
routes.IgnoreRoute("{*svg}", new { svg = #"(.*/)?.svg(/.*)?" });
This seem to be working fine with cassini (Visual Studio 2012 Buit-in Deployment Server) but when I deploy it to Azure I get a 404.
Is my IgnoreRoute statement right ? or any other solutions ? all other images, style sheets seems to work ok.
Thanks a lot in advance.

You never have to ignore routes for files that physically exist on disk, the routing module will not try to route those requests. You only need to ignore routes to other virtual resources.
Azure web sites do not have a mime type configured for .svg files, at least at the end of last year they didn't. You can configure a mime type for svg in the <system.webserver> section of your web.config file:
<staticContent>
<remove fileExtension=".svg"/>
<mimeMap fileExtension=".svg" mimeType="image/svg+xml"/>
</staticContent>
The remove is there to prevent errors on servers that already have an entry for .svg. It's an error to add a duplicate fileExtension, but not an error to remove a non-existent extension.
More here: Configuration Tips For ASP.NET MVC 4 on a Windows Azure Website

Looking at Phil's Blog I think what you need is something like:
routes.IgnoreRoute("{*allsvg}", new {allsvg=#".*\.svg(/.*)?"});
Hope that helps.

What order are you declaring the routes? It could be that above that one you have default or catch-all a route that actually already handles the request and so your IgnoreRoute never gets hit.

Related

How do I reload asp.net configuration file cache?

I have an asp.net application that sets the configSource attribute on the rewriteRules element in web.config to point to a separate config file:
<rewrite>
<rules configSource="App_Data\Config\RewriteRules.config" />
</rewrite>
My web app makes edits to the RewriteRules.config file programmatically, but my web app does not pick up the configuration changes after the file is edited and saved.
I have tried calling HttpRuntime.UnloadAppDomain() after editing the file. This successfully restarts my app domain, but the changes in RewriteRules.config are still not picked up. I have tried adding RestartOnExternalChanges="true" to the rewrite element, but this is apparently not supported on the IIS rewrite module. I have also tried ConfigurationManager.RefreshSection("rewrite/rules") but this does not seem to have any effect. The only way I can get the changes to take effect is to edit and save the main web.config file, but I am trying to avoid doing this programmatically for security reasons.
I am confused as to why HttpRuntime.UnloadAppDomain() does not cause external config files to be re-read. Is this expected behavior? Does the config file cache somehow exist outside the bounds of the app domain? Is there any practical way to achieve what I am looking to do?
Dude, the problem with your case is, related configSection definition is not marked as restartOnExternalChanges="true" in definition. For example; we created a custom config section for storing application urls in an external file and we create a section definition in web.config file like
<section name="pageUrlFormats" type="Kahia.Web.Configuration.PageUrlFormats.PageUrlFormatsSection, Kahia.Web" restartOnExternalChanges="true" requirePermission="false" />
so that asp.net knows if any change occurs in related file:
<pageUrlFormats configSource="Config\PageUrlFormats.config" />
application domain restarts. This goes same for all config section definitions, including UrlRewrite module's definition.
What you have to do is, find definition of related module. In this scenario, it is at apphost.config at C:\Windows\system32\inetsrv\config\applicationHost.config
In that file, look for rule section definition, it starts like
<section name="rules"
You have to add restartOnExternalChanges="true" attribute to that config file.
IIS7 configuration system uses the same syntax as the .Net framework configuration system, but is a different implementation that has some behavior differences. The restartOnExternalChanges thing is a feature of the .Net framework configuration system that is not supported by the IIS7 configuration system. The url rewriter module uses the IIS7 configuration system.

How do I bypass Accept header validation in IIS?

I have a Nancy website hosted on ASP.Net with a number of custom routes. These routes include mappings which look like file paths (e.g. /path/to/xml_file.xml), but that resolve to HTML files which should display in the browser. For most files, this works correctly. However, with XML files (and possibly other mime types), I am getting a 406.0 HTTP error from IIS 8 Express explicitly stating that
HTTP Error 406.0 - Not Acceptable
The resource cannot be displayed because the file extension is not being accepted by your browser.
The request was rejected because it contained an Accept header for a MIME type that is not supported for the requested file extension.
Verify the MIME settings for the file extension that was requested to make sure this MIME type is acceptable.
Is there any web.config setting or other technique for bypassing this validation so that I don't get this error without having to rewrite the path logic? My Google searching is failing me. For example, I have found this IIS forum post linked from the SO Answer which talks about
map all reqests to ASP.NET and use the ASP.NET's StaticFileHandler to serve them
However, the post does not explain how to do this; nor does it seem applicable.
Edit: (Added error page image above)
As another tidbit, the Nancy route returns an explicit view of the form
return View["view_name", myModel];
And therefore, should bypass content negotiation.
While not a fix or answer per se, my current work around (for anyone who might be interested) is to tweak the routes to use a trailing slash. As an example:
"/path/to/xml_file.xml" // Still returns a 406.0 error
"/path/to/xml_file.xml/" // Works properly (notice the trailing slash)
Here's a link to the Rackspace knowledge center that shows how to change the MIME mapping for static content in the web.config file.
https://www.iis.net/configreference/system.webserver/staticcontent/mimemap
There's also this one from MS that's more in-depth.
https://www.iis.net/configreference/system.webserver/staticcontent/mimemap
They both feature this stanza from the web.config file.
<configuration>
<system.webServer>
<staticContent>
<remove fileExtension=".extension" />
<mimeMap fileExtension=".extension" mimeType="application/example" />
</staticContent>
</system.webServer>
</configuration>
If that's how to actually fix the 406.0 problem...

WebResource.axd not found

I can't get script files to load on my website. Everything else works fine. I haven't tried ScriptResource.axd however.
I have verified this issue exists on both cassini and IIS7.
I have verified my 64bit 4.0 web.config contains the mapping for WebResource.axd.
My system time is correct (I heard there may be issues with that).
I have verified that it works in other projects, so the culprit has to be my web application.
My web application is 4.0 MVC3 web application.
My web.config can be found here.
This error is killing me! Any help would be appreciated!
Your web.config file is amazing (it's not a compliment): in .NET Framework 4.0, it should be much shorter/lighter.
I think that your handler is declared in the wrong section :
<system.webServer>
<handlers>
<add name="WebResource" path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" />
</handlers>
</system.webServer>
Normally, the WebResource.axd handler is declared in "system.web" section :
<system.web>
<httpHandlers>
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
</httpHandlers>
</system.web>
I resolved a similar issue by adding read permissions for Everyone to the folder where the assembly containing the embedded resource was located. Clearly Everyone is overkill, but that might help others researching similar issues.
In our case some resources loaded (so I know the AssemblyResourceLoader was working) and it worked on one machine but not another.
This answer to another question helped me determine what assemblies were not working.
I solved this issue on a production machine running again aspnet_regiis:
%WINDIR%\Microsoft .NET\Framework\4.xxxx\aspnet_regiis -i
Probably the standard installation of the framework 4 went wrong.
Bit late but might help someone in the future...
I found that this can happen if the DLL of the web application you are delivering are newer than the current date time. For example, you put your web application on the production server where the server time is older than on your development machine.
Getting the server time in sync with the dev machine did the trick for me...
Absolutely solution is : https://web.archive.org/web/20211020131200/https://www.4guysfromrolla.com/articles/080906-1.aspx
when you check the .net framework code : https://github.com/Microsoft/referencesource/blob/master/System.Web/Handlers/AssemblyResourceLoader.cs
you can see the trick : at line 606
WebResourceAttribute wra = FindWebResourceAttribute(assembly, resourceName);
if the assembly does not have WebResourceAttribute it throws 404 error.
You can see at this line
if (resourceStream == null) {
if (resourceIdentifierPresent) {
LogWebResourceFailure(decryptedData, exception);
}
throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest));
}
so add the WebResourceAttribute to your AssemblyInfo.cs file like this :
[assembly: WebResource("FullNameSpace.SampleResourceFile.js", "text/javascript")]
I had this .axd issue with Umbraco on a production server, it drove me crazy until I found out that the server had different security and under Request Filtering, the extensions .axd and .asmx were not listed in the Allowed filenames by default, and the hosting company had the setting Allow unlisted file name extensions turned off, which was different to my development machine.
None of the previous solutions worked out for me. Although it took me some time, in the end it was as simple as this:
Plesk Admins, Please disable the Web Application Firewall to solve this issue.
Tools & Settings > Web Application Firewall > Turn Off
Cheers!
Colin's tip got me looking at my new webhost (InterServer). Turns out their Web Application Firewall was the culprit. Switch it to Detect Only or Off, and it's fine.

How to get TinyMVC .NET class Library to work on ASP.NET MVC 2?

I am trying to implement the TinyMCE Spellcheck plugin that uses GoogleSpell. The thing is I am trying to install it in an MVC environment.
I started by referencing the .NET class Library DLL (MoxieCode.TinyMCE) in my project.
Then, I added this code to my web.config:
<system.webServer>
<handlers>
<add name="TinyMCE" verb="GET,HEAD,POST" path="TinyMCE.ashx" type="Moxiecode.TinyMCE.Web.HttpHandler,Moxiecode.TinyMCE" />
</handlers>
<!--previously existing rules-->
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
I then added these lines to my tinyMCE.init({}); call:
plugins: "spellchecker",
theme_advanced_buttons3: "spellchecker",
spellchecker_languages : "English=en",
spellchecker_rpc_url : "TinyMCE.ashx?module=SpellChecker",
These steps are outlined in the tutorial here. I then followed instructions from this stack overflow post which recommended the following modification to global.asax to make it mvc friendly:
routes.IgnoreRoute("TinyMCE.ashx");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
Everything seems fine accept that when I browse to /TinyMCE.ashx i get this error:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /TinyMCE.ashx
Why can't asp.net mvc process that url?
Make sure the handler is being applied at the correct element in the web.config.
IIS supports 2 types of modes, an integrated mode and a classic mode.
The classic mode is the how versions previous to IIS 7 worked. Depending on that, you put the handlers in the web.config section that applies to asp.net, or in the section that is picked by IIS directly.
After a fair bit of frustration I stopped messing with it on localhost in VS 2010. I suspected that it was a problem relating to IIS configuration, so I uploaded the site to a sub-domain of the live server. It worked without any problem.
I'm not sure why the code didn't work on localhost but evidently, the steps I followed to execute TinyMCE .NET and GoogleSpell were correct because they work on the live server.

UrlRewriting.Net Module + IIS7 Equals Page.User == null?

I've used the UrlRewriting.Net module for a couple years now without any problems in Windows XP and Windows 2003. I just recently upgraded my home PC to Windows 7 and started developing a new website.
The plan was to use .html extensions and rewrite them to their .aspx counterparts using the UrlRewriting.Net module. Everything works flawlessly in VWD 2008, but when I try running it through IIS7 it is a different story.
When I try to access a page via the .html rewrite I can no longer access Page.User; it keeps returning null. If I hit the page using it's .aspx extension, Page.User is correctly populated. I should also mention that I have a LoginView controller in my Master Page and it suffers from the same symptoms: When accessing via .html extension it shows the AnonyousTemplate; When using .aspx extension it properly shows the LoggedInTemplate. I'm guessing the two are related.
[Note: I've also tried extensionless URLs and they exhibit the same problem]
The only way I've gotten it to work is to switch the application pool to Classic, which then requires me to add an ASP.Net ddl handler for the .html extension [otherwise it is handled by the StaticFileHandler and comes up as a 404 error]. However, I'd like my web app to run properly for people without having to fiddle around with IIS.
So I am left with several questions:
Does anyone have ideas as to why Page.User always equals null for .html => .aspx rewritten pages?
Why does it work in VWD 2008, but not IIS7?
What changed from IIS6 => IIS7 that could have caused this?
Any other thoughts on workarounds?
[Note: I just tried a .aspx => .aspx rewrite and it did not exhibit the problem. Not really what I want, but thought I should mention it.]
Just had a breakthrough with the UrlRewriting.Net module. This makes it work in Integrated Mode in IIS7:
<modules runAllManagedModulesForAllRequests="true">
After figuring it out I did a search on "runAllManagedModulesForAllRequests" and the first thing that popped up was Scott Guthrie's blog which actually talks about using it for this purpose.
Another approach that seems to work is to remove the Session module and readd it leaving the "Invoke only for requests to ASP.NET applications or managed handlers" checkbox unchecked. It looks like this in the web.config file:
<system.webServer>
<modules>
<remove name="Session" />
<add name="SessionManualAdd" type="System.Web.SessionState.SessionStateModule, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
It seems the problem is that the Session module doesn't execute for say '*.htm' files when HttpContext.RewritePath is used, but removing and readding the module in this fashion causes the Session handler to be executed for the request.
This solution was suggested on the thread below. Unfortunately Microsoft chose not to explain the reasoning behind this behavior fully:
http://connect.microsoft.com/VisualStudio/feedback/details/357248/context-rewritepath-disables-session-module-in-iis7
Microsoft included a fix for this issue (at least for extensionless urls) in Service Pack 1 for Win7 and Windows Server 2008 R2:
http://www.microsoft.com/download/en/details.aspx?id=5842
Also available as a hotfix: http://support.microsoft.com/kb/980368
After this patch is applied, ASP.NET 4 applications can handle requests for extensionless URLs. Therefore, managed HttpModules that run prior to handler execution will run. In some cases, the HttpModules can return errors for extensionless URLs. For example, an HttpModule that was written to expect only .aspx requests may now return errors when it tries to access the HttpContext.Session property.
After applying SP1 or the hotfix, no web.config changes are needed to make the session and forms auth work for extensionless URLs rewritten to asp.net pages/handlers/etc.
I don't know if this fixes anything for rewrites to static file extensions like .htm. My guess is, probably not. I would try to avoid setting runAllManagedModulesForAllRequests="true" in production environments, because it adds unnecessary overhead on static file requests.

Resources