Custom Route in ASP.NET MVC - c#

I'm trying to setup a custom route in ASP.NET MVC 4. I want my route accessible via
http://www.mydomain.com/high-school/student/1
In an attempt to setup this route, I've added the following in RouteConfig.cs
routes.MapRoute(
name: "HSStudentProfile",
url: "high-school/student",
defaults: new { controller = "Students", action = "HSStudentProfile" }
);
StudentsController.cs
public class StudentsController : Controller
{
public ActionResult HSStudentProfile()
{
return View("~/Views/Shared/Course/Index.cshtml");
}
}
If I visit the url mentioned above, I get a 403.14 error. If I update the route config to use
routes.MapRoute(
name: "HSStudentProfile",
url: "{controller}/high-school/student",
defaults: new { controller = "Students", action = "HSStudentProfile" }
);
It works, however, I have to change the URL path to
http://www.mydomain.com/Students/high-school/student/1
Is there a way to do this without having to have {controller} in my RouteConfig?

Related

Why does an ASP.NET MVC route have a name?

In an ASP.NET MVC 5 web application, there is a RouteConfig class that registers many routes. In all of the examples I have seen so far, only the "Default" route has a non-empty name. The URL pattern and default route values seem to be sufficient to correctly associate any URL to the controller and action to execute. So, is there any benefit to naming a route? For debugging or logging? Just for self-documenting the code?
For example:
public class RouteConfig
{
public static void RegisterRoutes( RouteCollection routes )
{
routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
// Most pages.
routes.MapRoute( name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "home", action = "index", id = UrlParameter.Optional }
// A special page.
// Should the route have a name?
routes.MapRoute( name: "",
url: "special",
defaults: new { controller = "special", action = "index", HttpVerbs = HttpVerbs.Get } );
}
}
The main reason to name a route is so that if you need a link to a route from somewhere in the app, you can reference the name. That way if the actual URL/path changes you don't break everywhere in the code that references that route.

MVC routing: routing to a concrete method in the controller

I couldn't get any good information on how to define a route to a contrete action in the selected controller. MSDN doesn't provide clean information on this. There is a mention of action parameter but it doesn't seem to be working.
What I want to achive is to route path like /vehicles/check*** to Check method in the VehiclesController.
A concrete invokation is /vehicles/check?licencePlate=XYZ =>
VehiclesController -> Check(string licenePlate)
I have this map but it does not work:
config.Routes.MapHttpRoute("VehicleTransactions", "Vehicles/Check",
new { controller = "Vehicles", action= "Check" });
Can it be done with MVC?
Thanks, Radek
MapHttpRoute is used for mapping Web API routes. For MVC Controller routes we tend to use MapRoute
So Assuming
public class VehiclesController : Controller {
public ActionResult Check(string licenePlate) {
//...
return View();
}
}
The route would be mapped to
routes.MapRoute(
name: "VehicleTransactions",
url: "vehicles/check",
defaults: new { controller = "Vehicles", action= "Check" }
);
Try this:
routes.MapRoute(
name: "VehicleTransactions",
url: "Vehicles/Check/{licencePlate}",
defaults: new { controller = "Vehicles", action = "Check", licencePlate = UrlParameter.Optional });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Set "VehicleTransactions" routing before of "Default" routing, because otherwise "Default" overwrite the other.
Special routes is set always before default routing.

Not receiving get parameters

I'm using ASP.NET MVC 5
I'm having issues with both routes and parameters.
I have this function in my ControllerBase
[HttpGet]
[Route("~/obtenerAngulos/{Conex_AT}/{Conex_BT}")]
public JsonResult obtenerAngulos(string Conex_AT, string Conex_BT)
{
return Json(
new
{
AT = Conex_AT,
BT = Conex_BT
}
, JsonRequestBehavior.AllowGet);
}
And I start having problems receiving the second parameter Conex_BT the Url.Action() returns this route http://localhost:53645/Base/obtenerAngulos?Conex_AT=Y&Conex_BT=y the problem, is Conex_BT is always null
Then I try to work with route and add the Data Anotation for it [Route("~/obtenerAngulos/{Conex_AT}/{Conex_BT}")] but with Url.Action() I keep getting the same route as before.
Even if I try to write it manually like http://localhost:53645/Base/obtenerAngulos/AA/BB I get
HTTP Error 404.0 - Not Found
I mention both problems because I'm pretty sure they are relationated.
Here is the route configuration
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Make sure you have enabled attribute routing on the route collection.
//enable attribute routes
routes.MapMvcAttributeRoutes();
//convention-based routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
This now means that the following should match obtenerAngulos/y/x
public class ControllerBase: Controller {
//Matches obtenerAngulos/y/x
[HttpGet]
[Route("~/obtenerAngulos/{Conex_AT}/{Conex_BT}")]
public JsonResult obtenerAngulos(string Conex_AT, string Conex_BT) {
//...
}
}
The tilde (~) on the method attribute is used to override any route prefixes if needed.
Routes are matched in the route table in the same order they are added. In your example you had convention based routes registered before attribute routes. Once a route is matched it no longer looks for other matches.
Reference Attribute Routing in ASP.NET MVC 5

How to use MVC route in ASP.NET WebAPI project

I have a web API and i want to add a few asp.net pages to manage aspects of the API.
In the WebApiConfig.cs file i have a couple of routes, with the following being used as my catch all route for the API.
config.Routes.MapHttpRoute(name: "CatchAll",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });
I want to add a new section that is prefixed by /control to push to the asp.net side of things. To do this i have added the following to RouteConfig.cs
routes.MapRoute(
name: "Default",
url: "control/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I have then added a standard controller that i will use to manage things.
public class ManageController : Controller
{
public ActionResult Index()
{
return Content("Works");
}
}
When i visit /control/manage in the browser i get the following error.
No type was found that matches the controller named 'control'
It looks like the route is being completely bypassed or at best, the catch all from the api route is catching it and giving it priority. IS there a way i can make the request catch this route without having to create a separate project?
The order of registration is matter
You need to register
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultMVC",
url: "control/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//..other routes.
}
}
in the RouteConfig.cs before
config.Routes.MapHttpRoute(name: "CatchAll",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });
in the WebApiConfig.cs file.
What happens in your case is that the /control/manage url is handled by CatchAll route thus mapping control to a controller and manage to an action
In order to do that register them in Global.asax in the following order:
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);

Routing with MapRoute C# MVC

I am trying to setup a map routing using the Web.Routing and Web.MVC. The issue is that I need to be able to grab a potion of an incoming URL so an i can re route the user. i have my MapRoute url grabbing the entire string but since the url has a ? within it, it does not grab the entire string. More specifically, it does not grab anything after the occurrance of the ?.
Is there any way to get past this?
Here is my maproute:
routes.MapRoute(
name: "OldEmailLink",
url: "{tag}",
defaults: new { controller = "ApIssues", action = "Task", id = UrlParameter.Optional }
);
When I debug this, I can get redirected to the action just that the string value of tag is:
default.asp
When tag should be:
default.asp?etaskid=32698
Given this url:
http://localhost1853:/accounting/ap/default.asp?etaskid=32698
Try this for the controller.
public class ApIssuesController : Controller
{
public ActionResult Task(Int32 etaskid)
{
}
}
And this as the Route Config
routes.MapRoute(
name: "OldEmailLink",
url: "accounting/ap/default.asp",
defaults: new { controller = "ApIssues", action = "Task", id = UrlParameter.Optional }
);

Categories

Resources