I've been trying to figure this out but can't find any answers to my problem. The problem I am having is with this url:
localhost:343434/Lev/Details/1/4/CON/2
This url will return a "Server Error in '/' Application". I know that my Action will return a value with theese parameters.
However, if I use the same route but with other parameters:
localhost:343434/Lev/Details/3/4/FHS/5
It will call the action and return the result. The "Server Error in '/' Application" only appears when using "CON"
The outpus is this:
The resource cannot be found.
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: /Lev/Details/1/4/CON/2
And this is my route:
routes.MapRoute(
"LevRoute",
"{controller}/{action}/{id}/{source}/{levtyp}/{Levid2}/{page}/{order}",
new { controller = "Lev", action = "Details", page = UrlParameter.Optional, order = UrlParameter.Optional }
);
Thanks for help in advance!
I've found a solution for my problem by adding this to my Web.config:
<configuration>
<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true"/>
</system.web>
</configuration>
You can use Route Debugger to debug routes
Related
I want to customize route in ASP.NET MVC.
With
#Url.Action("ViewDoc", "Home", new { FileName = "ABC.pdf" })
and
routes.MapRoute(
name: "",
url: "{controller}/{action}/{FileName}",
defaults: new
{
controller = "Home",
action = "ViewDoc",
FileName = UrlParameter.Optional
}
I get
http://localhost/Home/ViewDoc?FileName=ABC.pdf
How to get the below?
http://localhost/Home/ViewDoc/ABC.pdf
The code you have pasted is correct but the ordering in your route setup is probably wrong. Move the routes.MapRoute method to be above the default route and it should work as expected.
Regarding your 404 error:
I'm using the same kind of URL with a file name at the end and getting the same routing problem.
Just like you, I try to catch the call with a controller.
I think the problem is the URL is treated as a direct link to a file on the server and it will just try to go get the file instead of calling the controller. Not finding the file at the physical location suggested by the URL will trigger a 404 error.
The workaround I chose to use is adding a "/" character at the very end of the URL after the file name.
There are others.
I suggest you read this related question:
Dots in URL causes 404 with ASP.NET mvc and IIS
I was able get
localhost/Home/ViewDoc/ABC.pdf
with
public FileResult View(string FileName) {
and
routes.MapRoute( "", "Home/ViewDoc/{FileName}", new { controller = "Home", action = "ViewDoc" } );
For Error 404.0 added the below under
<add
name="AdfsMetadata"
path="/Home/ViewDocu/*"
verb="POST"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
I'm using ASP.NET MVC 3 and I would like to accept url as parameter for one of the action. But, I'm getting "HTTP Error 400 - Bad Request." error for the below example. How do I resolve this issue?
Example:
http://localhost:8343/http://google.com
Global.asax.cs:
routes.MapRoute(
"Default", // Route name
"{hostUrl}", // URL with parameters
new { controller = "Home", action = "Index", hostUrl = UrlParameter.Optional } // Parameter defaults
);
You need to use URL encoding for the parameter http://google.com.
So, navigate here:
http://localhost:8343/http%3A%2F%2Fgoogle.com
(I just used an online URL encoder tool.)
Use
HttpUtility.UrlEncode
or
Server.URLEncode
Depending where you are doing the encoding.
I fixed by following these steps.
Change Web project properties to "Use IIS Local Server" and check "Use IIS Express"
Add the following setting in Web.config inside :
<httpRuntime requestPathInvalidCharacters=""/>
I am attempting to produce a simple WebDAV server using MVC, and I have finally reached the stage where I need to serve up a requested file to the user.
I have a route set up that deals with traversing the directory structure "webdav/{*path}" which works fine, right up until the point where that path ends in a file name. At this point, it appears that IIS decides that it is a static file, and attempts to serve that file from the disk. As it isn't in the location specified in the URL, it returns a 404 error.
I don't have any freedom to change the url, I basically need it to be in the form, otherwise Windows Explorer can't work with it as a mapped drive:
GET /webdav/Test/Test2.txt
I've set the route to greedily match, as the directory structure can have as many levels. I've also set routes.RouteExistingFiles = true;
This is using IIS Express 8.0 on my development machine.
I've gone as far as setting up a blank MVC project just to test this, and this is the RegisterRoutes method:
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "WebDAVGet",
url: "webdav/{*path}",
defaults: new { controller = "WebDAV", action = "Get", path = "" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
So, going to /webdav/Test/Test2 hits the breakpoint in my controller, but going to /webdav/Test/Test2.txt gives me a 404.
Any suggestions?
I needed to add
<modules runAllManagedModulesForAllRequests="true">
to the web config.
Ah, I've been struggling with this for a few days now, I knew posting here would shift the blockage!
Another option is to add this to the <system.webserver> node in web.config:
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
I can vouch that this works on IIS 7.5.
For the record, I found this solution here.
I'm tying to enable the default routing in MVC.
I want every 404 request to redirect to DefaultController DefaultRout()
I found How can i make a catch all route to handle '404 page not found' queries for ASP.NET MVC?
But {*url} dosen't work i'm getting 404 and not redirecting to the default page.
My code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.ascx/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.IgnoreRoute("{resource}.gif/{*pathInfo}");
//http://localhost:4775/BW/A/Tasks
routes.MapRoute("Pages", "A/{controller}", new { controller = "Tasks", action = "InitPage" });
routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "Default", action = "DefaultRout" }
);
}
What am I missing?
Thanks
Rafael
Are you unable to use your web.config? I think this would be easier:
<customErrors mode="On" defaultRedirect="/error/default">
<error statusCode="403" redirect="/error/restricted"/>
<error statusCode="404" redirect="/Default/DefaultRoute"/>
<error statusCode="500" redirect="/error/problem"/>
</customErrors>
There are a few things that I would like to point here.
I notice that you have used many IgnoreRoute entries for physical files. You don't have to do that as the framework looks for the physical files matching the url by default before routing it. You can disable the physical file matching by turning RouteExistingFiles to true on the RouteCollection in Global.asax. In this case you haven't done that.
Secondly, the way you have set it up, any route but /A/{controller} will be caught by the catch all route (anything starting with * is a catch all route) that you have configured.
I have tried this configuration and it does catch all the other routes except the one mentioned above. One thing you have to keep in mind, however, is that the above configuration will still matching everything with the following type of url: /A/something/ because the second segment will always match the {controller} placeholder. To only match this url with the "Tasks" controller, you can define a constraint on the route as the following:
routes.MapRoute("Pages", "A/{controller}", new { controller = "Tasks", action = "InitPage" }, new {controller="Home"});
There is also a spelling mistake in your catch all route configuration. action = "DefaultRout" should be action = "DefaultRoute"
Hope this helps.
In trying to get my application to produce 404 errors correctly, I have implemented a catch all route at the end of my route table, as shown below:
routes.MapRoute(
"NotFound", _
"{*url}", _
New With {.controller = "Error", .action = "PageNotFound"} _
)
However, to get this working, I had to remove the default route:
{controller}/action/{id}
But now that the default has been removed, most of my action links no longer work, and the only way I have found to get them working again is to add individual routes for each controller/action.
Is there a simpler way of doing this, rather than adding a route for each controller/action?
Is it possible to create a default route that still allows the catch all route to work if the user tries to navigate to an unknown route?
Use route constraints
In your case you should define your default route {controller}/{action}/{id} and put a constraint on it. Probably related to controller names or maybe even actions. Then put the catch all one after it and it should work just fine.
So when someone would request a resource that fails a constraint the catch-all route would match the request.
So. Define your default route with route constraints first and then the catch all route after it:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "Home|Settings|General|..." } // this is basically a regular expression
);
routes.MapRoute(
"NotFound",
"{*url}",
new { controller = "Error", action = "PageNotFound" }
);
//this catches all requests
routes.MapRoute(
"Error",
"{*.}",
new { controller = "PublicDisplay", action = "Error404" }
);
add this route at the end the routes table
Ah, the problem is your default route catches all 3 segment URLs. The issue here is that Routing runs way before we determine who is going to handle the request. Thus any three segment URL will match the default route, even if it ends up later that there's no controller to handle it.
One thing you can do is on your controller override the HandleMissingAction method. You should also use the tag to catch all 404 issues.
Well, what I have found is that there is no good way to do this. I have set the redirectMode property of the customErrors to ResponseRewrite.
<customErrors mode="On" defaultRedirect="~/Shared/Error" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="~/Shared/PageNotFound"/>
</customErrors>
This gives me the sought after behavior, but does not display the formatted page.
To me this is poorly done, as far as SEO goes. However, I feel there is a solution that I am missing as SO does exactly what I want to happen. The URL remains on the failed page and throws a 404. Inspect stackoverflow.com/fail in Firebug.
My Solution is 2 steps.
I originally solved this problem by adding this function to my Global.asax.cs file:
protected void Application_Error(Object sender, EventArgs e)
Where I tried casting Server.GetLastError() to a HttpException, and then checked GetHttpCode.
This solution is detailed here:
ASP.NET MVC Custom Error Handling Application_Error Global.asax?
This isn't the original source where I got the code. However, this only catches 404 errors which have already been routed. In my case, that ment any 2 level URL.
for instance, these URLs would display the 404 page:
www.site.com/blah
www.site.com/blah/blah
however, www.site.com/blah/blah/blah would simply say page could not be found.
Adding your catch all route AFTER all of my other routes solved this:
routes.MapRoute(
"NotFound",
"{*url}",
new { controller = "Errors", action = "Http404" }
);
However, the NotFound route does not seem to route requests which have file extensions. This does work when they are captured by different routes.
I would recommend this as the most readable version. You need this in your RouteConfig.cs, and a controller called ErrorController.cs, containing an action 'PageNotFound'. This can return a view. Create a PageNotFound.cshtml, and it'll be returned in response to the 404:
routes.MapRoute(
name: "PageNotFound",
url: "{*url}",
defaults: new { controller = "Error", action = "PageNotFound" }
);
How to read this:
name: "PageNotFound"
= create a new route template, with the arbitrary name 'PageNotFound'
url:"{*url}"
= use this template to map all otherwise unhandled routes
defaults: new { controller = "Error", action = "PageNotFound" }
= define the action that an incorrect path will map to (the 'PageNotFound' Action Method in the Error controller). This is needed since an incorrectly entered path will not obviously not map to any action method
I tried all of the above pattern without luck, but finally found out that ASP.NET considered the url I used as a static file, so none of my request was hidding the single controller endpoint. I ended up adding this snipper to the web.config
<modules runAllManagedModulesForAllRequests="true"/>
And then use the below route match pattern, and it solved the issue:
routes.MapRoute(
name: "RouteForAnyRequest",
url: "{*url}",
defaults: new { controller = "RouteForAnyRequest", action = "PageNotFound" }
);