Implementing Attribute Routing - c#

I'm trying to get a handle on attribute routing in MVC.
Initially, the routing for my sitemap controller was as follows:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "SitemapXml",
url: "sitemap.xml",
defaults: new { controller = "Sitemap", action = "Index" }
// Additional mappings...
}
}
That works fine. But then I tried commenting out the SitemapXml routing above and instead adding an attribute in my controller.
// GET: Sitemap
[Route("sitemap.xml")]
public ActionResult Index()
{
// Generate sitemap
}
I also added the following line at the end of RegisterRoutes:
routes.MapMvcAttributeRoutes();
But now when I navigate to domain.com/sitemap.xml, I get a page not found error.
Questions:
What steps am I missing to get my routing attribute to work?
Since mappings can now be specified in two places (as attributes or set directly in the RouteCollection), what happens when those two places contradict each other?

if you remove the extension .xml , your attribute routing will work perfectly. And its better to use the extension related code in action method.
Also make sure your route config looke like (routes.MapMvcAttributeRoutes(); should exist before default route)
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);

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.

Is there any way to make a custom route in C# MVC? [duplicate]

This question already has answers here:
Routing in ASP.NET MVC, showing username in URL
(2 answers)
Closed 4 years ago.
I am new to C# MVC,
This is my default RouteConfig File,
public class RouteConfig
{
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 }
);
}
}
When I run my project http://localhost:50382 it redirects the default home index method.
How can I build custom url like http://localhost:50382/somestringcode and call a specific ActionMethod. Something Like a custom route that points to specific ActionMethod and the stringcode will be passed as parameter.
public ActionResult Method1( string code)
{
return View();
}
What you are searching for is attribute routing. That means specifying URL routes explicitly.
First, you need to enable it
routes.MapMvcAttributeRoutes();
Then add Route attribute to desired action:
[Route("")]
public ActionResult Method1( string code)
{
return View();
}
Since code parameter is simple type, it will be searched in request URL.
You need to do something like this, where controller1 is the controller name that contains Method1, and make sure you place this first, and leave the original route config, so when it doesn't match this route, it will use default route.
Please note this is bad practice, and it will fail in case route is trying to access default action for a controller "Index" as #stephen mentioned in the comments below, and that's why I would suggest adding a prefix ex "Action1" to the route.
routes.MapRoute
(
name: "Method1",
url: "Action1/{code}",
defaults: new { controller = "controller1", action = "Method1", code = "default"}
);

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

Make an MVC controller the default in WebAPI project

I have created my first WebAPI project to learn, which had an index.html page in the root of the project. I set that page as Startup. All working fine. But, I want to use an MVC controller to call the View instead.
So I created a new MVC controller in my Controller folder called "DefaultController". In it, there's a method:
public ActionResult Index()
{
return View();
}
I created a View folder, and off that, a Default folder, in which, I created an Index.cshtml file.
When I start the project, it calls my old index.html. So, I changed the startup to be the index.cshtml, which is wrong - know. MVC calls a controller method. So, I'm trying to work out - how do I call the controller method in my DefaultController?
I think I need to change my routes?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
My plan is to use cshtml pages (instead of html pages) to make use of layouts and allow controllers to initiate the views. Each view will the use an api call back to my WebApi controllers to do the data handling.
Does that seem like a good way to handle my WebAPI/KnockoutJs project?
I just need to know how to get the controller to be the default.
When removing the index.html page, I get the error:
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.
I think you need to add the controller name to the defaults object as in:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You need to register both WebAPI routes and MVC routes:
All this should be done in Application_Start method in Global.asax.cs file:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
GlobalConfiguration.Configure(WebApiConfig.Register) is used to configure WebApi (and register api related routes)():
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
RouteConfig.RegisterRoutes(RouteTable.Routes); is used to register MVC routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You also need verify that the DefaultController that you created is MVC controller (inherits from System.Web.Mvc.Controller) and not WebAPI controller
According to my experience, when you want to call the index.cshtml, in the route config you have to define the controller like this in the RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The controller supposed to be "Home", and the Action is "Index". But, this maproute is for default one. How about if you want to add another one?
routes.MapRoute(
"Article",
"articles",
new { controller = "News", action = "ArticleList" }
);
You can write freely as shown above where "Articles" is the name of maproute and the "articles" is the url. And it would become like this (http://www.domain.com/articles) if you compile controller News and Action ArticleList. And "..../articles" is something you replace (No need define controller or action) and you don't need to open www.domain.com/News/ArticleList it's enough to go to url www.domain.com/articles and the maproute would be automaticaly route to controller news and action articlelist.
That's only my point of view about how maproute works.
CMIIW :)

ASP.NET MVC Routes: How do I omit "index" from a URL

I have a controller called "StuffController" with a parameterless Index action. I want this action to be called from a URL in the form mysite.com/stuff
My controller is defined as
public class StuffController : BaseController
{
public ActionResult Index()
{
// Return list of Stuff
}
}
I added a custom route so the routes are defined like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Custom route to show index
routes.MapRoute(
name: "StuffList",
url: "Stuff",
defaults: new { controller = "Stuff", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
But when I try to browse to mysite.com/stuff I get an error
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
The URL mysite.com/stuff/index works fine. What I am doing wrong?
HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.
The error indicates that you have a virtual directory (probably a physical one) in your project called /Stuff. By default, IIS will first reach this directory and look for a default page (for example /index.html), and if no default page exists will attempt to list the contents of the directory (which requires a configuration setting).
This all happens before IIS passes the call to .NET routing, so having a directory with the name /Stuff is causing your application not to function correctly. You need to either delete the directory named /Stuff or use a different name for your route.
And as others have mentioned, the default route covers this scenario so there is no need for a custom route in this case.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Passing the URL `/Stuff` will match this route and cause it
// to look for a controller named `StuffController` with action named `Index`.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
It seems that your scenario is covered fine by default route, so there is no need for a custom Stuff one.
As to why the error is thrown, the fact that action is listed in defaults does not mean that it is actually becoming a part of a route. It should be mentioned in the route, otherwise it appears as there is no action at all. So what I think happens here is that first route is matched, but it cannot be processed as there is no action specified, so MVC passes request on to IIS, which throws the named error.
The fix would be simple:
// Custom route to show index
routes.MapRoute(
name: "StuffList",
url: "Stuff/{action}",
defaults: new { controller = "Stuff", action = "Index" }
);
But again, you shouldn't need that at all.

Categories

Resources