How can we allow dots in ASP.NET MVC urls? - asp.net

I have a website developed in MVC 5 that perform search in inventory and the url is like this
http://localhost:56099/search/SQUARE
This url works, it redirects to Search controller and Index action with search query as SQUARE and gives the correct result. But, if I enter 2 dots as a search query it just takes me to my root page. The url will be like this
http://localhost:56099/search/..
it's strange because same thing works when passing single dot or multiple dots, so I can't find any technical reason why it is getting neglected.
I have done following things in Web.Config:
<modules runAllManagedModulesForAllRequests="true"> for accepting others characters also in search query.
relaxedUrlToFileSystemMapping="true"
But no success and I can't find any real reason for this weird behaviour. Any advice.

you should register the search route in your "RouteConfig.cs" file
routes.MapRoute(
"SearchRoute",
"Search/{*pathinfo}",
new { controller = "Search", action = "ActionName"});

You have the problem with .., because .. in your case is detected as relative URL, which indicates moving up to the parent directory(or root in your case), essentially stripping off everything up to the previous slash in the the Base URI.
UrlRoutingHandler in web.config should help you.
<system.webServer>
<handlers>
<add name="UrlRoutingHandler"
type="System.Web.Routing.UrlRoutingHandler,
System.Web, Version=4.0.0.0,
Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
path="/Search/*"
verb="GET"/>
</handlers>
</system.webServer>
Then every URL starting with /Search will be considered as MVC URL.
Also you could try:
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="true" />
</security>
</system.webServer>

Related

ASP.net MVC4 WebApi route with file-name in it

I'm trying to get the following (and similar) urls to work in my ASP.net MVC4/WebApi project:
http://127.0.0.1:81/api/nav/SpotiFire/SpotiFire.dll
The route responsible for this url looks like this:
config.Routes.MapHttpRoute(
name: "Nav",
routeTemplate: "api/nav/{project}/{assembly}/{namespace}/{type}/{member}",
defaults: new { controller = "Nav", assembly = RouteParameter.Optional, #namespace = RouteParameter.Optional, type = RouteParameter.Optional, member = RouteParameter.Optional }
);
It works just fine if I remove the . in the file-name, or if I add a slash behind the URL, but that also means I can't use the Url.Route-methods etc. The error I get is a generic 404-error (image below).
I've tried adding <httpRuntime targetFramework="4.5" relaxedUrlToFileSystemMapping="true" /> to my web.config, and I've also tried adding
<compilation debug="true" targetFramework="4.5">
<buildProviders>
<remove extension=".dll"/>
<remove extension=".exe"/>
</buildProviders>
</compilation>
And none of it seems to work. So my question is basically, how can I get this URL to work, and map correctly?
You could add the following handler to the <handlers> section of your <system.webServer>:
<add
name="ManagedDllExtension"
path="api/nav/*/*.dll"
verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"
/>
This will make all requests containing .dll be served through the managed pipeline. Also notice how I have limited them only to the GET verb to limit the performance impact.
Found it. What's needed is this (and maybe some of the things I've added above in the original post):
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
My trade off was to append /end to the end of route. .'s are ignored before the last /.
The equivalent URL would be http://127.0.0.1:81/api/nav/SpotiFire/SpotiFire.dll/end.
The benefit being that you don't get a performance hit on your assets.

ASP MVC 2 handlers for extensionless urls in IIS 7.5 not working

I have a project with a HttpHandler that's supposed to execute when an extensionless url like this localhost/foo/bar is requested. I got this properly working on a local Visual Studio development server (by using <httpHandlers> in <system.web> instead of <system.webServer><handlers>) but this functionality doesn't work when deployed to IIS 7.5 (Standard 404 error: http://i.imgur.com/YuNjT.jpg). This issue is not restricted to extensionless URLs (I might add any extension at the end and the issue remains) but my desired functionality is to use extensionless url in this scenario. I googled some information that extensionless URLs may cause some issues that's why I mention it here. The AppPool is set to Integrated. I did aspnet_regiis.exe -i. I have Http Redirection feature installed on the IIS server. Here's my handlers config:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<add name="FileDownloadHandler" path="/Home/Files/*" verb="*" type="MvcApplication1.FileDownloadHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode" />
</handlers>
<directoryBrowse enabled="true" />
</system.webServer>
And here's my routing setup:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("home/files/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I'm guessing the code is fine but something's off with my IIS configuration. Can anyone guide me in the right direction? I've googled for days now and I couldn't find a solution that helped me. Here's a sample project (works on local VS dev server but not on my IIS):
http://mapman.pl/MvcApplication1.zip
When you build (and deploy to your local IIS) the above solution try requesting an url like this: http://localhost/MvcApplication1/Home/Files/foobar
Thanks in advance,
Bartek
In your web.config replace:
path="/Home/Files/*"
with:
path="Home/Files/*"
The reason for that is because when you host your application in IIS, there's a virtual directory name and the correct path is /MvcApplication1/Home/Files/* instead of /Home/Files/*. This problem is easily solved by using a relative urls in your path attribute.

ASP.NET MVC Url Route supporting (dot)

I hope that you can help me with the below problem.
I am using ASP.NET MVC 3 on IIS7 and would like my application to support username's with dots.
Example: http://localhost/john.lee
This is how my Global.asax looks like: (http://localhost/{username})
routes.MapRoute(
"UserList",
"{username}",
new { controller = "Home", action = "ListAll" }
);
The applications works when I access other pages such as http://localhost/john.lee/details etc.
But the main user page doesn't work, I would like the app to work like Facebook where http://www.facebook.com/john.lee is supported.
I used below code and it didn't work for me at all:
<httpRuntime relaxedUrlToFileSystemMapping="true" />
I was able to use below code and get the app to accept dots but I definitely wouldn't like to use below code for many different reason, please tell me there is a way to overcome this problem.
<modules runAllManagedModulesForAllRequests="false" />
Add a UrlRoutingHandler to the web.config. This requires your url to be a bit more specific however (f.e. /Users/john.lee).
This forces every url starting with /Users to be treated as a MVC url:
<system.webServer>
<handlers>
<add name="UrlRoutingHandler"
type="System.Web.Routing.UrlRoutingHandler,
System.Web, Version=4.0.0.0,
Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
path="/Users/*"
verb="GET"/>
</handlers>
</system.webServer>
Just add this section to Web.config, and all requests to the route/{*pathInfo} will be handled by the specified handler, even when there are dots in pathInfo. (taken from ServiceStack MVC Host Web.config example and this answer https://stackoverflow.com/a/12151501/801189)
This should work for both IIS 6 & 7. You could assign specific handlers to different paths after the 'route' by modifying path="*" in 'add' elements
<location path="route">
<system.web>
<httpHandlers>
<add path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" />
</httpHandlers>
</system.web>
<!-- Required for IIS 7.0 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ApiURIs-ISAPI-Integrated-4.0" path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</location>
I was facing the same issue. So the best solution for me is:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
<system.webServer>
For anyone getting an 'Cannot create abstract class' exception when using the UrlRoutingHandler approach, it's likely due to:
Using a restricted 'path' (e.g. path="/Files/*") in your web.config declaration, and
A folder/path with the same name exists in your project
I don't think the dot is the problem here. AFAIK the only char that should not be in the user name is a /
Without seeing the route that matches john.lee/details it's hard to say what's wrong, but I'm guessing that you have another route that matches the url, preventing the user details route from being matched correctly.
I recommend using a tool like Glimpse to figure out what route is being matched.

Dynamic URL REWRITING for QueryStrings

hello please help me for this question
i have the following url --> www.sample.com/news.aspx?id=45
i want pass "id" in the query string to news.aspx and show this news, but due to url rewriting the url is changed to this --> www.sample.com/news/my-news-45/
How to extract "id" from the query string?
Thanx for your help
you can manually done URL rewriting but The downside of manually writing code can be tedious and error prone. Rather than do it yourself, I'd recommend using one of the already built HttpModules available on the web for free to perform this work for you.
Here a few free ones that you can download and use today:
http://urlrewriter.net/
http://www.urlrewriting.net/149/en/home.html
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>
<system.web>
<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
</httpModules>
</system.web>
<rewriter>
<rewrite url="~/products/books.aspx" to="~/products.aspx?category=books" />
<rewrite url="~/products/CDs.aspx" to="~/products.aspx?category=CDs" />
<rewrite url="~/products/DVDs.aspx" to="~/products.aspx?category=DVDs" />
</rewriter>
</configuration>
The HttpModule URL rewriters above also add support for regular expression and URL pattern matching (to avoid you having to hard-code every URL in your web.config file). So instead of hard-coding the category list, you could re-write the rules like below to dynamically pull the category from the URL for any "/products/[category].aspx" combination:
<rewriter>
<rewrite url="~/products/(.+).aspx" to="~/products.aspx?category=$1" />
</rewriter>
the complete reference can be found on this linke
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

Problem mapping HttpHandler --> HTTP Error 404 Not Found

I am having problems trying to map an HttpHandler in the web.config.
This is the relevant config bit:
<httpHandlers>
<add verb="*" path="*.hndlr" type="MyAssembly.MyHandler, MyAssembly" validate="false" />
</httpHandlers>
When I navigate to http://localhost/myApp/whatever.hndlr I am getting a server error 404 (not found).
It's the 1st time I am hooking up an HttpHandler so I might be missing something - any help appreciated!
UPDATE:
I managed to get it working using both answers so far - who's able to explain why it works gets the answer marked!
This is my config (won't work if you don't have both - I am running IIS7 in classic mode)
System.web:
<httpHandlers>
<add verb="*" path="*MyHandler.hndlr" type="MyAssembly.MyAssemblyHandler, MyAssembly" validate="false"/>
</httpHandlers>
System.webserver:
<handlers>
<add name="MyHandler" verb="*" path="*MyHandler.hndlr" type="MyAssembly.MyAssemblyHandler, MyAssembly" validate="false" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"/>
</handlers>
Are you using IIS7, if so is the application pool running in classic or pipelined mode? If it is IIS7 in pipelined mode then the handler reference needs to go into the following section
<system.webServer>
<handlers>
</handlers>
<system.webServer>
rather than in the following section.
<system.web>
<httpHandlers>
</httpHandlers>
</system.web>
Just as a guide for those stuck with this problem I found the crucial attribute to be..
resourceType="Unspecified"
I originally followed a Microsoft example to set this up and they had it as
resourceType="File"
which just kept giving me 404 errors. My HTTPHandler is returning graphics.
Hope this helps :)
i am using IIS7, the solution is:
in section
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx" type="CVOS.MyDocumentHandler"/>
</httpHandlers>
<system.web>
and section
<system.webServer>
<handlers>
<add name="pdfHandler" verb="*" path="*.ashx" type="CVOS.MyDocumentHandler" />
</handlers>
</system.webServer>
What is the extension of your handler? If you are using a custom extension like .hndlr you may also need to add a ScriptMap in IIS and point it to the ASP.NET runtime so that IIS can forward the request to the correct processor.
In IIS7 go to your website
Under the IIS group go to Handler Mappings
Under Actions click Add Script Map
Set Request Path to *.hndlr
Set Path to the ASP.NET runtime (%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll) or whatever version you are running.
Then in your web.config you will need to register the handler in the appropriate section as described in the other answer.
It is also possible to experience this error if you have set up the handler for 32 bit, but you are running in 64 bit (or vice versa). It's easy to set up both and have all the bases covered.
Note "preCondition", and "scriptProcessor" differences.
<handlers>
<add name="MyHandler_32bit" verb="*" path="*MyHandler.hndlr" preCondition="bitness32" type="MyAssembly.MyAssemblyHandler, MyAssembly" validate="false" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" />
<add name="MyHandler_64bit" verb="*" path="*MyHandler.hndlr" preCondition="bitness64" type="MyAssembly.MyAssemblyHandler, MyAssembly" validate="false" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" />
</handlers>
None of the previous answers worked for me.
I'm using IIS 8.5, .Net v4.0, Integrated, and was still getting a 404 with the following handler config:
<system.webServer>
<handlers>
<add name="testEmail" path="*.em" verb="*" type="MyApp.testRazorEmailHandler, MyApp" resourceType="Unspecified" requireAccess="Script" />
</handlers>
</system.webServer>
I enabled tracing and found the following :
116. -HANDLER_CHANGED
OldHandlerName testEmail
NewHandlerName System.Web.Mvc.MvcHandler
NewHandlerModules ManagedPipelineHandler
NewHandlerScriptProcessor
NewHandlerType System.Web.Mvc.MvcHandler, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
As you can see it looks like it had correctly picked up the request using my custom HttpHandler testEmail but MVC had stolen it.
I opened my route definitions in RouteConfig.cs and found that adding:
routes.IgnoreRoute("{resource}.em");
I got it to ignore requests meant for my Handler.
Hope this helps someone - I was tearing my hair out!
Hopefully my solution will help others. On a server move from IIS6 to 7.5, both .Net 4.0 Integrated, I had a Captcha control that quit working. It turns out that removing this attribute preCondition="integratedMode,runtimeVersionv2.0" from the <add> node in <system.webserver><handlers> resolved the issue.
This seems to be an edge case, but I had a customer where our httpHandler used in our application did not work on any of their servers. The handler pointed to an .ashx page and it was called from JavaScript.
The handler mapping showed up in IIS, the handler factory was there, but I would get a 404 when the browser requested the ashx page associated with the handler. After many different attempts to fix we finally browsed to the file in IIS on the server and it specifically showed a 404.7 being returned with this message.
•Request filtering is configured for the Web server and the file extension for this request is explicitly denied.
•Verify the configuration/system.webServer/security/requestFiltering/fileExtensions settings in applicationhost.config and web.config.
If you get this then Request Filtering is enabled for the .ashx extension at either your app or site level. Go to the Request Filtering option in IIS at both your site and app level and verify that the extension is not blocked. There are two different ways Request Filtering can be configured.
The default seems to be that it explicitly blocks only file extensions that are configured in the list (blacklist). The other way it can be configured is that only files specifically configured as allowed in the list are let through (whitelist). This second option is how the customer had configured all of their Windows Servers by default and it turns out that the .ashx file extension was not in the list of allowed extensions.
This is the first thread that appears when I look for a verb that responds with a 404. In my case the solution was a configuration of VS
Tools > Options > Web projects > [x] Use 64 bit version
Sorry, my VS is in spanish

Resources