routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); [duplicate] - asp.net-mvc

What is routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
I cannot find any .axd file in my project, can I remove this route rule?

.axd files don't exist physically. ASP.NET uses URLs with .axd extensions (ScriptResource.axd and WebResource.axd) internally, and they are handled by an HttpHandler.
Therefore, you should keep this rule, to prevent ASP.NET MVC from trying to handle the request instead of letting the dedicated HttpHandler do it.

Some Background
If you open up this file:
%WINDIR%\Microsoft.NET\Framework\version\Config\Web.config
you will find this within the file:
<add path="WebResource.axd"
verb="GET"
type="System.Web.Handlers.AssemblyResourceLoader"
validate="True" />
That is basically telling the Asp.NET runtime: "Hey asp.net dude, if a request comes for WebResource.axd then use AssemblyResourceLoader to process the request."
Please do note that WebResource.axd is NOT a file but simply a map (if I may say) to AssemblyResourceLoader. It is the name under which the handler is registered. On my machine, I found the following .axd handlers:
<add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
<add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
<add verb="*" path="*_AppService.axd"
Ok, so what does that handler do?
The AssemblyResourceLoader knows how to look for embedded files within an assembly so it can serve it (send it to the client i.e. a browser). For example, in asp.net web forms, if you use the validation controls, they depend on some javascript to show the errors on the web page. However, that javascript is embedded in an assembly. The browser needs the javascript so you will see this in the html of the page:
<script src="/YourSite/WebResource.axd?d=fs7zUa...&t=6342..." type="text/javascript"></script>
The AssemblyResourceLoader will find the assembly where the javascript is embedded using the information in the querystring and return the javascript.
Back to the Question
So to answer the question, what is:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
That is telling the routing engine that we will not be processing those requests that match that route pattern. In other words, we will not process .axd requests. Why? Because MVC itself is an HttpHandler similar to .axd and .aspx and many other handlers that are in the web.config file. The MVC handler does not know how to process the request such as looking for embedded resources in an assembly-the AssemblyResourceLoader knows how to do that. MVC knows how to do, well everything it does which is beyond the scope of this question and answer.

The route with the pattern {resource}.axd/{*pathInfo} is included to prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
Read link:
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx
You can also specify that routing should not handle certain URL requests. You prevent routing from handling certain requests by defining a route and specifying that the StopRoutingHandler class should be used to handle that pattern. When a request is handled by a StopRoutingHandler object, the StopRoutingHandler object blocks any additional processing of the request as a route. Instead, the request is processed as an ASP.NET page, Web service, or other ASP.NET endpoint. You can use the RouteCollection.Ignore method (or RouteCollectionExtensions.IgnoreRoute for MVC applications) to create routes that use the StopRoutingHandler class.

Take a look in the below link:
http://haacked.com/archive/2008/07/14/make-routing-ignore-requests-for-a-file-extension.aspx

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered.

Related

ASP.Net MVC4 Routing not working - reserved word?

In short, I have an MVC web app that has a proxy class to marshall requests to another web app under the context of the logged in user.
This all works fine except that some of the outgoing links (i.e. inbound links to my MVC app) from the other web app contain the url "/views".
These requests should be mapped according to this route:
routes.MapRoute(
name: "TableauViews",
url: "views",
defaults: new { controller = "Tableau", action = "Views" }
);
But it never happens. If I change the name of the controller action to something else and enter the corresponding url in a browser, it works.
This leads me to suspect that there is some problem mapping a url containing the word "views" as part of its path. Can anyone confirm this?
The issue is the order of operations. Views is a physical folder and a route. The ASP.NET HttpHandler will read the web.config and block anything going to views before the route handler picks up the URL. If you look at the web.config file in your views folder (where your views are actually stored) you will likely see something like this:
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
Also, later in the config there may also be this:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
This is your culprit. I would suggest either naming your route something more like "externalViews" or simply "external" might help. The other alternative is to remove the line above from your views web.config, but this could result in some undesirable behavior.
This article deals with restricting only certain types of files from being delivered instead of blocking all that may be helpful for you.
http://blog.falafel.com/Blogs/j-tower/2014/03/28/loading-javascript-files-from-the-views-folder-in-asp-net-mvc
I couldn't find anything specifically saying "views" is a reserved word, but the article http://haacked.com/archive/2010/04/29/allowing-reserved-filenames-in-URLs.aspx describes how to relax the rules on what words can be used.

MVC Route to Action for Javascript file

I am trying to add a mvc route to generate a javascript from the controller. I have added the following route and it doesn't work:
routes.MapRouteWithName(
"DataSourceJS", // Route name
"Scripts/Entities/{controller}/datasource.js", // URL with parameters
new { controller = "Home", action = "DataSourceJS"} // Parameter defaults,
, null
);
But if I change the route to not have the ".js" and I navigate to "Scripts/Entities/{controller}/datasource" it works. But I need to have the .js file extension on there, how do I make this work?
how do I make this work?
IIS intercepts the request because it contains a file extension and hijacks it thinking it is a static file and not passing it to your application.
To make it work you should tell IIS not to do that. Inside the <system.webServer> section you could add the following handler to indicate that requests with the specified pattern should be handled by the managed pipeline:
<system.webServer>
<handlers>
...
<add name="ScriptsHandler" path="Scripts/Entities/*/datasource.js" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Some people might also tell you to use:
<modules runAllManagedModulesForAllRequests="true" />
but I wouldn't recommend you doing that because this means that all requests to static resources will now be flowing through the managed pipeline which could have a negative performance overhead for your application. The handler syntax allows you to selectively enable this only for certain route patterns and HTTP verbs.

IIS hosting ASP.NET MVC site gives http 404 for urls containing 'web.config'

Requesting a page from IIS (hosts ASP.NET MVC 3 site) with url containing web.config gives 404 error. Urls with app.config have no problem. Local Visual Studio development server has no issues with this type of urls.
1 - What are any other special words other than web.config, being handled this way by IIS?
In request filtering page/hidden segments tab this is the current state:
I guess these are not special words, because IIS handles words like bin, App_code etc without a problem.
Answer: I guess these are the words being handled by IIS this way. So these are the default words I think and this list is configurable (new items can be added to this list).
2 - Are there any quick fixes (like by web.config modification) to handle urls with these special words?
Btw, I am not trying to serve the web.config file. Url format is : www.mysite.com/es/web.config/1
This is part of the IIS configuration under the Request Filtering section:
You can add/remove filters.
However, I do believe this is a really bad idea to remove web.config from it.
http://www.iis.net/configreference/system.webserver/security/requestfiltering
Cause:
As you already shown a snapshot of IIS configuration. These are reserved folder & files in .Net application, so IIS want to preserve those for security.
URLs which contain these strings as returned as 404 response only if these comes in before ? AND exactly between 2 slashes /../ OR at last. Eg: www.example.com/bin/anything.ext OR www.example.com/folder/sub/web.config
IIS match these string anywhere coz, web.config can we at any directory level.
If anything is with those string are there THEN page will be served by IIS. Eg: www.example.com/bin-folder/anthing.ext OR www.example.com/sub/bin.html OR www.example.com/-web.confing/page.aspx are OK.
I recommend to use some other words with these strings OR use at end of URLs with extensions, so that it will not come between two slashes.
Eg: www.example.com/en-web.config/1 OR www.example.com/en/1/web.config.aspx
Even then I have one Tricky Solution:
If you really need these strings exactly without other words in URL THEN I recommend to use URL-ReWrite.. This may not be quick at whole but except 2nd step its quick and handy, coz second step depends on your application.
1- Add this rule in IIS at top level:
regexp match: (/web|^web)\.(config$|config/) //OR as your requirement
re-write to: handler.aspx?url={REQUEST_URI}
<rule name="web-config" stopProcessing="true">
<match url="(/web|^web)\.(config$|config/)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="handler.aspx?url={REQUEST_URI}" appendQueryString="false" />
</rule>
2- In handler.aspx (or in any other language page) check the url GET variable and respond accordingly.Request.QueryString("url")
Do it carefully coz here you are controlling security.
I suggest to include the actual page content to response in handler.aspx or handler.php only rather then redirecting etc.
Before including content verify URL first(by regular expression etc.), and include content hardcoded, do not take any part of URL in to variable and use that variable in response-inclusion-code.
3- After that at last from IIS manager, In a specific website go to request filtering->hidden segment tab and delete the desire string. Eg: web.config. This step can be done by web.config also:
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="209715200" />
<hiddenSegments>
<remove segment="web.config" />
</hiddenSegments>
</requestFiltering>
</security>
Now, IIS will serve the page and your handler page will show the output with exact same URL in user browser.

Invoke ASP.NET MVC Controller When Requesting .html file

I need to add some new life to a legacy application :)
I'd like to call an MVC controller when a "static" HTML page is requested in order to add some markup to the page before returning it to the client.
I tried to follow the approach found in this thread: How to read web.config settings in .html page?
...but even though I have this route defined:
routes.MapRoute(
name: "Topic",
url: "html/{fileName}.html",
defaults: new { controller = "Topic", action = "Index" });
the controller is not being called. I have my web.config defined with:
<remove name="WebServiceHandlerFactory-Integrated" />
<add name="HTML" path="*.html" verb="*"
type="System.Web.UI.PageHandlerFactory"
resourceType="File" preCondition="integratedMode" />
I suspect that I need to call something else besides the PageHandlerFactory or perhaps the issue is something entirely different.
UPDATE: My dev environment is working with integrated pipeline mode, but I need to check if my production environment will support it.
If you do this:
routes.RouteExistingFiles = true;
You should find this works - even without the handler addition. In the controller you can load the HTML directly using the HostingEnvironment.VirtualPathProvider's GetFile method and do something with it - or better still just use a normal MVC view that renders the same content as the static file, just with your additions.
Although be aware that this means any files that are potentially caught by any routes will be pushed into the MVC pipeline. This isn't generally a concern, however, if decent separation of routes and physical paths is used.
I setup the same situation as you and it worked well for me, so you have the key components in place. Some things to keep in mind for the testing and troubleshooting:
Your web.config does need the build provider for the html extension:
<system.web>
<compilation>
<buildProviders>
<add extension=".html"
type="System.Web.Compilation.PageBuildProvider" />
</buildProviders>
</compilation>
</system.web>
A copy and paste of your handlers works for me, so that looks good.
And a copy and paste of your MapRoute works for me too, although I used the default Home controller in a clean project. So as a double check just confirm that you have a controller called Topic with an ActionResult method called Index().
And make sure that your url is localhost.com:{port}/html/test.html with the /html/ in the path since your rule asks for that.
Another good test is to change your MapRoute to use aspx instead and test an aspx page and see if that works. That will confirm whether or not it's the IIS mappings or if it's the MVC rules. If it works with aspx then the issue is related to the handler, but if it fails with aspx too then it's something with MVC.
Also confirm that you're using IIS Express and not Cassini. Cassini will not handle that correctly, but IIS Express will. You can confirm by right-clicking on your project and you should see a menu option called "Use Visual Studio Development Studio...". That will only exist if you are currently using IIS Express.

MVC3 Web Application Will Not Publish

I am trying to learn MVC 3, so I am a noob. For now, I just want to make a basic site, that is an HTML page using jQuery and CSS. While I am using MVC, I don't really need a model, since there is not really any data being passed to the application. However, this is creating a problem for me, because I am getting a HTTP 403.14 Forbidden error when I try to publish this site. I think that there is something wrong with the way the application is structured that will not allow it to execute properly when I got to localhost:1081 web site. Here is all I have:
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
}
This just returns the view of Index.cshtml.
Index.cshtml:
#{ViewBag.Title = "My Web Site";} <h2>Web Site Title</h2>
All of my HTML code was put into _Layout.cshtml. jQuery and CSS are used. The site works fine when I do the debug option, but when I try to publish it gives me 403.14 forbidden. I have run the inline command aspnet_regiis -i and it seemed to work, but did not allow the project to run.
Global.asax:
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
);
}
If I move the code in _Layout to Index, it doesn't work. Is there a way I should be linking this to Index.cshtml?
Web.config:
<system.webServer>
<defaultDocument enabled="true">
<files>
<add value="_Layout.cshtml" />
</files>
</defaultDocument>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
I do not want directory browsing, and I have tried to play with this option as well. If I enable, it allows me to see the contents but does not render the page.
So two questions: 1.) Do I need to have a model, even though I am not passing any data to the application, just trying to render a site? 2.) Is my site set up / structured properly or what exactly am I doing wrong here?
Thanks,
Nick
No, you don't need a model.
First, don't use the default document. MVC overrides the default document handling and uses the route system.
Second, you don't want to try and use the Layout page as your document. Layout is like a master page, and is used to create a wrapper around your real document.
Third, saying "will not publish" means that you are having problems actually publishing the site via the publish mechanism. Your problem is not that you can't publish, because obviously it is doing so, but that your site isn't executing.
Fourth, 403.14 means it's trying to list the contents of directory, but this shouldn't happen if MVC is configured correctly because MVC's routing takes over. This means you have a problem somewhere in the asp.net pipeline.
Where are you publishing to? Did you configure IIS to setup a site at this location? Given that you are trying to access the site from a different port number, It would seem to me that you have not setup IIS to do this and are instead trying to use the same port that's used for debugging.
In order to publish a site, IIS must be configured to use that location.

Resources