c# MVC 5 RouteConfig redirection - c#

Recently I had to update my mvc webapplication so that a basic entity of the system is displayed in the UI with a different literal.
Lets say
Previously I had: "Vessels"
Now I am asked to make it: "Ships"
The urls where mapped as by convention: mysite/{controller}/{action}/{id}
So I had urls like :
mysite/Vessels/Record/1023
mysite/Vessels/CreateVessel
I did all the renaming in the User Interface so that the titles and labels are changed from Vessel to Ship and now I a m asked to take care of the urls as well.
Now, I do not want to rename the Controller names or the ActionResult method names, because it is some heavy refactoring and because it is VERY likely, that the literals will soon be required to change again... ;-)
Is there any quick solution for me by editing just the RouteConfig, or something like that, that could do the work with a couple of lines coding?

Yeah, just register the route that will map your VesselsController actions:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Vessels", // Route name
"Ship/{action}Ship/{id}", // URL with parameters
new { controller = "Vessel", id = "" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
Also make sure to register your route before default one. Because, in other case, default route will be executed first and you will get an exception because no ShipController is defined in your application.

Related

URL Routing MVC 5 Asp.net

I know about routing in MVC. I added a new MapRoute under RegisterRoute method in RouteConfig.cs class and successfully called my function with the URL http://localhost:53363/package/PackageDetail/mypackage/5.
However, my question is do i have to add different Map Routes for every method or is there any better way ? Like in PackageController class you can see i have two methods one methods takes PackageId and PackageName and the other takes only PackageId. So do i have to register different Map Routes or not ?
RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Package",
url: "Package/PackageDetail/{packageName}/{packageId}",
defaults: new { controller = "Package", action = "PackageDetail", packageName = UrlParameter.Optional, packageId = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
PackageController.cs :
[HttpGet]
public ActionResult PackageListing(int packageId = 0)
{
return View();
}
[HttpGet]
public ActionResult PackageDetail(string packageName = "", int packageId = 0)
{
return View();
}
Despite the fact that Muhammed's answer will work, it is very repetitive, especially if you're using the same style of routes for multiple types.
There are a few things to consider before deciding upon a single approach to routing. The main one is why have both the name and ID in the route? If you want a more SEO friendly URL structure, don't bother with the ID at all.
If you have multiple products within the same type that have identical names, then there's no point in including the name as part of the URL since that won't get a user where they want to go by itself. In that event, just leave the original route.
However, if you have several different controllers (or actions) with a similar name/id structure for the routes, you'll be far better served with making your custom route more generic.
routes.MapRoute(
name: "NameAndId",
url: "{controller}/{action}/{name}/{id:int}",
defaults: new
{
controller = "Package",
action = "PackageDetail",
name = UrlParameter.Optional,
id = UrlParameter.Optional
});
Keep this above the default route, and this will redirect not just
/Package/PackageDetail/Deluxe/5
but also allow you to have stuff like this:
/Meals/Menu/Dinner/3
That may not necessarily be applicable for you in this project, but since you're learning MVC, this is a good skill to pick up. The more generic you're able to maintain your route definitions, the less you'll need to repeat it. Of course, if this is a one-time special route, there's nothing wrong with using the attributes.
Also to answer your final question, you do not need to create another custom route, because your PackageListing method will be routed through the default route that was provided when you created your project.
If you want to override default route url and generate custom url then you need to register route in route config file.
You can pass Package name and package Id as below.
http://sitename/Package/PackageListing?packageId=1
http://sitename/Package/PackageDetail?packageName=packagename&packageId=1
but if you want to generate URL as below than you need to add route in route.config file.
http://sitename/Package/PackageListing/1
http://sitename/Package/PackageDetail/packageName/1

Is it possible to set a global RoutePrefix for an entire MVC application?

I have an MVC site that we are using just to host our new checkout process. There is a rewrite rule in our ARR server in place so that any requests for https://www.oursite.com/checkout go to this new application instead of the legacy site.
This means that every request to the new application starts with /checkout which leaves us with the slightly unsatisfactory situation of having every controller in the site decorated with [RoutePrefix("checkout")].
Is there a way that I can set a global route prefix that automatically applies to all controllers in the application? We don't have a universal base controller that we own to put an attribute on. The only options I could think of are to go back to the old fashioned routing:
routes.MapRoute(
"Default",
"checkout/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
I'd much prefer to use Attribute Routing, so I want to call something like routes.MapMvcAttributeRoutes(globalPrefix: "checkout");
How can I accomplish this?
I found out a way to do it, not sure if it's best practice but it seems to work just fine. I noticed that the MapMvcAttributeRoutes method can take an IDirectRouteProvider as argument.
It took a bit of guesswork but I was able to write a class that derives from the framework's DefaultDirectRouteProvider and overrides the GetRoutePrefix method:
public class CheckoutPrefixRouteProvider : DefaultDirectRouteProvider
{
protected override string GetRoutePrefix(ControllerDescriptor controllerDescriptor)
{
return "checkout/" + base.GetRoutePrefix(controllerDescriptor);
}
}
I can then use this new class as follows:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(new CheckoutPrefixRouteProvider());
}
}

How to call a controller outside of an area?

In my application I have an area "Member".
Outside this member area I have a folder named "Generic" which is having a controller "DataBindController".
This controller will be used in all areas. So to keep it common, i am keeping it in a separate folder outside of areas.
My route config is as follows:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var ObjRoute = routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults:new {controller = "Login", action = "MemberLogin", id = UrlParameter.Optional},
namespaces: new string[] { "MyApp.Generic.*" }).
DataTokens = new RouteValueDictionary(new { area = "Member"});
//ObjRoute.DataTokens["UseNamespaceFallback"] = false;
}
}
Here's the project directory structure.
The Test controller inside Generic folder is as follows:
namespace MyApp.Generic
{
public class DataBindController : Controller
{
public ActionResult Test()
{
return Content("Test");
}
}
}
I am getting following error when I call the test controller using "http://localhost/MyApp/Generic/DataBind/Test"
Error in Path :/MyApp/Generic/DataBind/Test The controller for path
'/MyApp/Generic/DataBind/Test' was not found or does not implement
IController.
Please give me some idea on this issue.
your address doesn't match your defined route. Generic is just a folder. MVC doesn't care about the folder your controller is in.
the correct one should be like this :
http://localhost/MyApp/DataBind/Test
so the DataBind will be the controller and Test the Action.
Update:
your route is
{controller}/{action}/{id}
When you have Generic in your address, Asp.net matchs parts this way : Generic is the Controller, DataBind is Action and Test is the Id. of course it can't find such a thing. But when you remove Generic , every part goes to its real place.
To have Generic in the address, you should change your route to this:
Generic/{controller}/{action}/{id}
To read more about routing :
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs

Does an existing action get routed to before a mapped route is attempted?

If an action exists on a controller, does asp.net-mvc route to that action before attempting to process any custom mapped routes?
Example.
Say I have the following controller
public class ShopController : Controller
{
public ActionResult Shop(Category category)
{
// returns some result
}
public ActionResult CartItemCount()
{
// returns some result
}
}
And I have registered the following route in my route collection:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Shop",
"Shop/{category}",
new { controller = "Shop", action = "Shop", category = UrlParameter.Optional } // Parameter defaults
);
}
What would happen if I had the following URL?
http://www.example.com/Shop/CartItemCount
Edit
I confused myself by thinking that the name of the mapped route was related to how it was processed. That is not the case, when it comes to url matching the name of the route does not matter.
As it turns out I had another route defined just above the one I gave in the example. This route, though named differently, was getting matched. I didn't even think to check it because, as I said, I thought the name given to a route somehow impacted the matching.
The routes decide which action to use. If there are no routes defined, you wont hit an action even if it exists. Install RouteDebugger and fire off your url. It will tell you ALL routes that it matches and which one it has actually used.

Routing with Multiple Parameters using ASP.NET MVC

Our company is developing an API for our products and we are thinking about using ASP.NET MVC. While designing our API, we decided to use calls like the one below for the user to request information from the API in XML format:
http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&api_key=b25b959554ed76058ac220b7b2e0a026
As you can see, multiple parameters are passed (i.e. artist and api_key). In ASP.NET MVC, artist would be the controller, getImages the action, but how would I pass multiple parameters to the action?
Is this even possible using the format above?
Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:
public ActionResult GetImages(string artistName, string apiKey)
MVC will auto-populate the parameters when given a URL like:
/Artist/GetImages/?artistName=cher&apiKey=XXX
One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:
public ActionResult GetImages(string id, string apiKey)
would be populated correctly with a URL like the following:
/Artist/GetImages/cher?apiKey=XXX
In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
If you wanted to support a url like
/Artist/GetImages/cher/api-key
you could add a route like:
routes.MapRoute(
"ArtistImages", // Route name
"{controller}/{action}/{artistName}/{apikey}", // URL with parameters
new { controller = "Home", action = "Index", artistName = "", apikey = "" } // Parameter defaults
);
and a method like the first example above.
Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.
A detailed discussion is available here:
http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
Summary:
First you enable attribute routing
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
Then you can use attributes to define parameters and optionally data types
public class BooksController : Controller
{
// eg: /books
// eg: /books/1430210079
[Route("books/{isbn?}")]
public ActionResult View(string isbn)
You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:
http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
api_key=b25b959554ed76058ac220b7b2e0a026
That could be:
routes.MapRoute(
"ArtistsImages",
"{ws}/artists/{artist}/{action}/{*apikey}",
new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
);
So if someone used the following route:
ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/
It would take them to the same place your example querystring did.
The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

Categories