I have an MVC application and am using the standard routeconfig that routes /Controller/Action/Id
I want it to additionally capture /Controller/Action.html as the url and as well and point to /controller/action also.
I am using a jquery library that I have no control over, and a function requires a url that points to a webpage or an image. However, it doesn't appear to understand that ends without an extension(.html, .php etc) is a link to html and throws an error.
Edit: I tried as the commenter below suggested, and still can't seem to get it to work. Here is my route config.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("routeWithHtmlExtension",
"{controller}/{action}.html",
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
This Url works:
http://localhost:14418/Album/Test
This one does not:
http://localhost:14418/Album/Test.html
In web.config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
...
</system.webServer>
If you set up the following route, it will work:
routes.MapRoute("routeWithHtmlExtension",
"{controller}/{action}.html",
new {controller = "Home", action = "Index" }
);
Related
I have been searching a lot for the way that I can handle 404 error for redirect it to a page designed and named 404 error.
Some of the articles say that I should do some changes in Route config. I changed it and now below codes are my route.config but still, it does not work properly
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//404 ERRORS:
routes.MapRoute(
name:"404-PageNotFound",
url: "{}",
new { controller = "Home", action = "Pagenotfound" }
);
}
I mean still, when I run the project and I type the wrong address, it shows default 404 page not the one I designed - Pagenotfound.cshtml.
Copy and paste the following code between <sytem.web> tags in web.config page. When occuring 404 error, it redirect to Pagenotfound.cshtml page.
<customErrors mode="On">
<error statusCode="404" redirect="/Error/Pagenotfound"/>
</customErrors>
Also, add [HandleError] attribute on top of Controller pages.
I am trying to prevent user to access abc.com/Home/Index, instead i want user to be able to access home page via abc.com only. I use the following code but not work.
// This code restict user to access abc.com/home/index
// Only allow user to access abc.com/home
routes.MapRoute(
"OnlyAction",
"{action}",
new { controller = "Home", action = "Index" }
);
// This code does not work, I am expecting this code to allow
// user to access home only at abc.com
routes.MapRoute(
"Home",
"",
new { controller = "Home", action = "Index"}
);
You just need to ignore the URL:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Ignore the alternate path to the home page
routes.IgnoreRoute("Home/Index");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Then the server will return a 404 not found instead of a page.
Of course, if you wanted to remove all of the alternate paths for the entire application, you would need to remove the default values of the Default route, which will make them required.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Ignore the alternate path to the home page
routes.IgnoreRoute("Home/Index");
routes.MapRoute(
name: "Home",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
Now you won't be able to access the home page by /Home/, either (which is another route that accesses it using the default route).
Of course, the best option is to use the canonical tag to ensure no additional routes that may slip through damage your SEO score.
<link rel="canonical" href="http://example.com/" />
I have an nicely functioning ASP.Net MVC site using the simple standard routing scheme:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
My client would like to redirect the static pages to a secondary site, so that they can edit them, template-style, at will. The pages that actually do something will remain on the original site.
What I need to do is set up routes for my functional views/controller-actions and redirect the remaining urls to the external site regardless of whether or not the specified url has a matching controller/action. I don't want to mess with the existing code, but use routing to execute some of the pages and redirect from others.
For example:
mysite.com/sponsors/signup would be executed
mysite.com/sponsors/information would be redirected
Even though the sponsors controller contains actions for both signup and information and there are existing views for both signup and information.
So far, I have been unable to wrap my head around a way to do this.
Any ideas?
You can use attribute routing to make it easier.
Your RouteConfig will look like below:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); // enable attribute routing
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
}
Then you can add an action like below:
public class SponsorsController : Controller
{
[Route("sponsors/information")]
public ActionResult RedirectInformation()
{
return RedirectPermanent("http://yoururl.com");
}
}
EDIT ONE
If you don't want to use attribute routing, you are still going to need the action but your RouteConfig will look like below:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//The order is important here
routes.MapRoute(
name: "redirectRoute",
url: "sponsors/information",
defaults: new { controller = "Home", action = "RedirectToInformation"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
In routing like this, if the match is found the rest of the routes are ignored. So, you'd want to put most specific route on top and most general in the bottom
EDIT TWO (based on the comment)
You can put a simple appsettings in Web.config like below:
<appSettings>
<add key="UseAttributeRouting" value="true" />
</appSettings>
Then in RegisterRoutes you can read it like below and make the decision.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseAttributeRouting"]))
{
routes.MapMvcAttributeRoutes();
}
else
{
routes.MapRoute(
name: "redirectRoute",
url: "sponsors/information",
defaults: new {controller = "Home", action = "RedirectToInformation"}
);
}
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
The browser sometimes caches these redirects, so you may want to recommend clearing browser caches if you change these settings. Check this superuser post for clearing the cache for Chrome.
You have two options
i) This is perfect use case to write a custom mvchandler that is instatiated by a custom IRoutehandler. You can follow this example.
http://www.eworldui.net/blog/post/2008/04/aspnet-mvc---legacy-url-routing.aspx.
ii) You can write HttpHandler for these matching paths you can redirect them to the other site.
Step 1: add this to RouteConfig.cs
routes.IgnoreRoute("yourwebpage.aspx");
Step 2: create new file at root of website called "yourwebpage.aspx"
Step3: Inside yourwebpage.aspx put:
<%
Response.RedirectPermanent("http://yourwebsite.com");
%>
It is pretty simple.
Create an Action
public ActionResult ext(string s)
{
return Redirect(s);
}
And in Routeconfig file add
routes.MapRoute(name: "Default17", url: "routeyouwant", defaults: new { controller = "Home", action = "ext", s = "http://externalurl.com" });
Using MVC, I have an html form helper in my view:
using (Html.BeginForm("ActionOne", "ControllerOne")) ...
Using the default route, the output for the action attribute is as expected:
<form action="/ControllerOne/ActionOne" ...
But registrering a new route with seemingly no matches affects the output.
Routing code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("testRoute", new Route("MyUrl", new MvcRouteHandler()));
routes.MapRoute("Default", "{controller}/{action}", new { controller = "Home", action = "Index"});
}
Output:
<form action="/MyUrl?action=ActionOne&controller=ControllerOne"
Is this by design or am I mising something fundamental?
Cheers!
I have experienced this exact problem. I'm not sure exactly why the System.Web.Mvc.HtmlHelper seems to just use the first non-ignore route in the routetable to generate links etc from but I have found a workaround for the "BeginForm" issue.
If you have named your "Default" route in the Global.asax.cs, for example:
routes.MapRoute("Default", "{controller}/{action}", new {controller = "Home", action = "Index" });
Then you can use the Html.BeginFormRoute method and call the name of the "Default" MVC route, then name the controller and action specifically, resulting in the correct url:
using (Html.BeginRouteForm("Default", new { controller="YourController", action = "YourFormAction" })) { }
HTH
Try this
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("testRoute", new Route("MyUrl/***{action}/{controller}***", new MvcRouteHandler()));
routes.MapRoute("Default", "{controller}/{action}", new { controller = "Home", action = "Index"});
}
I think it should solve your problem.
Add this before default route
routes.MapRoute("", "ControllerOne/ActionOne", new { controller = "ControllerOne", action = "ActionOneOne"});
I'm trying to add a route that shows some data based on a string parameter like this:
http://whatever.com/View/078x756
How do I create that simple route and where to put it?
In your global.asax.cs file, you add the following lines:
routes.mapRoute(
// The name of the new route
"NewRoute",
// The url pattern
"View/{id}",
// Defaulte route data
new { controller = "Home", action = "Index", id = "078x756" });
Make sure you add them before the registration of the default route - the ASP.NET MVC Framework will look throught the routes in order and take the first one that matches your url. Phil Haack's Routing Debugger is a valuable tool when troubleshooting this.
Routes are usually configured in the Application_Start method in Global.asax. For your particular case you could add a route before the Default one:
routes.MapRoute(
"Views",
"View/{id}",
new
{
controller = "somecontroller",
action = "someaction",
id = ""
}
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new
{
controller = "home",
action = "index",
id = ""
}
);
Routes are added in the global.asax.cs
Example of adding a route:
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
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 = "" } // Parameter defaults
);
routes.MapRoute(
"WhatEver"
"{View}/{id}",
new {controller = "Home","action = "Index", id="abcdef"}
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
}