Define Custom Route asp.net mvc5 - asp.net

I want to assign a route in asp.net mvc application.
What i have is a Measurement Controller. I have 3 types of Measurement in the business scenario.
Blouse
Lhenga
Pardi
Due to which i wanted the url to be like Measurement/Create/Lhenga
Just like this, I want to create Measurement/Create/Blouse and Measurement/Create/Pardi routes.
Although I know I will have to write a route in RouteConfig.cs class.
I have written
routes.MapRoute(
"MeasurementRoute",
"{controller}/{action}/{type}/"
);

public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Contact",
url: "Contact",
defaults: new {
controller = "Contact", action = "Address"
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home", action = "Index", id = UrlParameter.Optional
}
);
}
Every MVC application must configure (register) at least one route, which is configured by MVC framework by default
You can also configure a custom route using MapRoute extension method. You need to provide at least two parameters in MapRoute, route name and url pattern. The Defaults parameter is optional.
You can register multiple custom routes with different names. Consider the following example where we register "Contact" route.
As shown in the above code, URL pattern for the Contact route is Contacts/{id}, which specifies that any URL that starts with domainName/Contacts, must be handled by ContactController. Notice that we haven't specified {action} in the URL pattern because we want every URL that starts with Contact should always use Index action of ContactController. We have specified default controller and action to handle any URL request which starts from domainname/Contacts.
MVC framework evaluates each route in sequence. It starts with first configured route and if incoming url doesn't satisfy the URL pattern of the route then it will evaluate second route and so on. In the above example, routing engine will evaluate Contact route first and if incoming url doesn't starts with /Contacts then only it will consider second route which is default route

Related

Adding attribute route breaks config-based route (.NET MVC5)

So, we're updating a project from web forms to .NET MVC. To support other applications that deep link into our application, I'm trying to add attribute routes to the relevant controller actions that mimic the old web forms paths.
I have an event action on the Home controller. The configuration has a route for this to remove the controller name.
routes.MapRoute(
name: "eventdetails_nohome",
url: "event/{id}/{occurrenceid}",
defaults: new { Controller = "Home", action = "Event", occurrenceid = UrlParameter.Optional },
constraints: new { id = #"\d+", occurrenceid = #"\d+" }
);
That route works just fine for routes like http://myapp/event/123/456, and the default routing like http://myapp/home/event?id=123&occurrenceid=456 also works.
So far so good, but if I add this route attribute to the action:
[Route("~/ViewEvent.aspx")]
public ActionResult Event(int id, int occurrenceid)
Then the only route that works is http://myapp/ViewEvent.aspx?id=91918&occurrenceid=165045. The routes that worked before start returning
Server Error in '/' Application.
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: /event/123/456
I've used the routedebugger extension, and I can verify that even with the attribute route, my old route is still the first to work. So why would I be getting "resource cannot be found" errors?
Note: as a workaround, I've found that I can just do a traditional route configuration like
routes.MapRoute(
name: "Legacy event",
url: "ViewEvent.aspx",
defaults: new { Controller = "Home", action = "Event" }
);
I'm still curious why the attribute route would break existing routes, though, as I thought you were supposed to be able to use both at the same time.
Take a look at Attribute Routing in ASP.NET MVC 5
Another article with the same heading
Attribute Routing in ASP.NET MVC 5
Attribute routes overrides the convention based route. If you use more than one URL for action, you can use multiple route attributes on the action...
[Route("event/{id:int}/{occurrenceid:int}")]
[Route("event")]
[Route("~/ViewEvent.aspx")]
public ActionResult Event(int id = 0, int occurrenceid = 0) {
return View();
}
The following URLs all routed to the above action.
http://myapp/event/123/456
http://myapp/home/event?id=123&occurrenceid=456
http://myapp/ViewEvent.aspx?id=91918&occurrenceid=165045

Url Rewrite: Should www re-writing be in the app or the web server?

I have to redirect non-www urls to use www. I have a choice of doing this in IIS 7 or code this logic in my ASP.Net application.
In terms of portability I would've thought writing this in the application itself might be better.
Is there a preferred method for achieving this or is it just preference?
When you do this in IIS7, all it does is modify your Web.Config files for you. I would have said that that was the conventional way of doing things.
http://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module
I think, it is more rational to do this in the application. For example we have it defined like that:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"User", // Route name
"u/{user}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Hence we have plenty of flexibility and can have specific tokens in our links, etc. Yet if there was no need for that - we would use IIS base. So, I guess - whatever tickles your pickle here :)

MVC route conflicts with service route

I'm trying to convert the existing web project to MVC. I made a standard MVC project in VS 2012. It added routing configuration. My existing project already contained routing entry used by WCF services. So now routes are configured like this:
// Was here before, used by services
routes.Add(new ServiceRoute("AppServer", new WebServiceHostFactory(), typeof(MyService)));
// the rest is added by vs to configure a default controller
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I realized that service part should always go first because it is more restrictive. Service doesn't work if it is put to the end. But now the problem is that
#Html.ActionLink("text", "MyAction", "MyController")
now generates me the links of type
http://localhost/AppServer?action=MyAction&controller=My
instead of
http://localhost/My/MyAction
what I would expect.
Does anyone know how to make service route and mvc-related routes "live in peace" i.e. not to affect each other?
Try and put the MapRoute on top but add a fourth parameter for contraints, like this:
new { controller = "regex-for-!=-AppServer" }
This way, when creating a link the helper will use the first route found, but still incoming requests to "/AppServer" will be skipped and processed by the ServiceRoute.

rename controllers asp.net mvc

I have a bigger project with about 9 controllers. Now at the end of the project the url requeirement change. How to deal best with this situation - renaming the controllers seems just too cumbersome ... I need to change all links in servercode and javascript
Your problem can be solved by changing your existing routes. In your global.asax you'll find a code fragment like this
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
That maps an URL '/Controller/Action/Id' to Controller, Action and Id. You can provide routes like this
routes.MapRoute(
"RefactoredRoute", // Route name
"SomeChangedURLBase/{action}/{id}", // URL with parameters
new { controller = "Controller", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
to route requests to /SomeChangedURLBase... to be handled by Controller.
Be aware that these routes should be registered before the default route to avoid that links generated in views point to the default route and generate the old URL.
you could change the routings in global.asax
just change the method RegisterRoutes
here you can find some more informations.
http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs
http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
cheers

What's the proper configuration or routing so that Default.aspx, "", and "~/" don't get routed?

I've got glimpse.
it's highlighting an empty line on the routes tab
Match Area Url Data constraints DataTokens
True Root -- --
Locally it seems cassini doesn't properly emulate a virtual directory so changing from localhost to localhost/site doesn't seem to grant any additional testing insight.
Local testing
cassini (windows 7 (32 and 64 bit are available))
doesn't seem to use or allow integrated
deploy environments
IIS7 Integrated
Tried a http routing setting to push / to /site however I ran into trailing slash issues (/site would route to /site/site, while /site/ would work as expected
web.config
tried a few ways of setting runAllManagedModules=false with various errors
using <remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" /> that was linked
tried
I need /site (/~) requests to go to ~/Default.aspx
would love for a way to have / go there as well.
How do I do it?
To enable Default.aspx as the default url you just need to remove your route handling so that there's no catch-all route.
By default all MVC 3 projects have:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This is a catch-all route that will match everything you pass in your url. If you remove this and no path is defined then it will use whatever you set up as your default page in your web.config.
To map /site to Default.aspx you just need to add a special route:
routes.MapPageRoute("SitetoDefault", "site", "~/Default.aspx");
This will see the /site and route it to your default page.
You'll have to be careful when adding any other routes to your routing table. All of them will have to have a controller defined or you'll have to add a routing constraint. Something like this:
//controller defined
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
//route constraint
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}, // Parameter defaults
new { controller = "^(products)|(account)|(home)$" }
);
Here is more detail on creating more complex routing: http://www.asp.net/mvc/tutorials/creating-a-custom-route-constraint-cs

Resources