first match routes must specify both controller and action? - c#

Below is my code:
//inside UseMvc method:
routes.MapRoute(
name: "NewRoute",
template: "/",
defaults: new { controller = "Home"});
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
we know that routing system will only find the first match route, so the first one 'NewRoute' should match the route when the application starts, because it has no action method, so I should get a 404 error page, but when I run the app, the "default" route was used, which display a normal page. so why the "NewRoute" doesn't get selected by routing system in the first place?

The fact is that NewRoute is checked first, but routing could not find a matched action.Then it will match the next routing rule.
If you enable the Logging level to Debug in appSettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Debug"
}
}
}
and change the startup CompatibilityVersion to 2.1 (asp.net core 2.2 has another kind of EndPoint mechanism)
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
You could see the whole process in the log when you run the application:
dbug: Microsoft.AspNetCore.Routing.RouteBase[1]
Request successfully matched the route with name 'NewRoute' and template '/'
dbug: Microsoft.AspNetCore.Mvc.Internal.ActionSelector[3]
No actions matched the current request. Route values: controller=Home
dbug: Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler[3]
No actions matched the current request. Route values: controller=Home
dbug: Microsoft.AspNetCore.Routing.RouteBase[1]
Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller Core22MVC.Controllers.HomeController (Core22MVC).
It matches twice and select the default route.

Related

Default controller giving me a "No HTTP resource was found that matches the request URI" -"No type was found that matches the controller named 'tab'

I'm trying to access an app on my localhost connected to IIS with the following endpoint I'm trying to hit https://api.url.com/api/tab. I have a TabController.cs in my Controllers folder. I also have a Views/Tab/Index.cshtml file and am wondering why I'm getting the following two errors:
<Error>
<Message>No HTTP resource was found that matches the request URI 'https://api.url.com/api/tab'.</Message>
<MessageDetail>No type was found that matches the controller named 'tab'.</MessageDetail>
</Error>
I have the same folder structure for a controller named Footer, and I'm able to access https://api.url.com/api/footer successfully. I've included my WebApiConfig.cs and RouteConfig.cs code below:
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
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 }
);
}
I've a feeling it's something quite obvious I'm missing as I'm a bit new to .NET and the MVC structure. So any point in the right direction would be greatly appreciated.
You trying to access the MVC Controller (inherited from the System.Web.Mvc.Controller) as if it's the Web API Controller (inherited from the System.Web.Http.ApiController). As you know API controllers have their own routing configuration, which is completely separate from the rest of
the application. Therefore, to access an action method from the regular MVC controller don't use api prefix in the URL. Just enter https://api.url.com/tab to call the default action method in the tab controller.

Issue with MVC Routing?

I have an issue in Routing in MFA where link like
Project_Name\Controller\Index is working, whereas
Project_Name\Controller\ is not working
This is happening for only some controllers after being deployed in a server.
I am getting the following error:
403 - Forbidden: Access is denied.You do not have permission to view this directory or page using the credentials that you supplied.
Is there any further configuration values that needs to be considered?
In RouteConfig we define the route path like this
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
So the controller you are using may have Index action method and the URL works.
But if your controller does not contain Index method or it is having parameters then it will not work.
This is a possible solution that you might create an action method named Index in all those controllers.
for more, you need to share some more details.

Default route is not working with Area route

I am creating an application in ASP.NET Core 2.2. In the Startup.cs file there was already a default route and I defined one other route for an admin area:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "admin",
template: "{area=Admin}/{controller=User}/{action=Index}/{id?}");
});
The admin area is authorized by an Admin role using [Authorize(Roles = "Admin")]. But when I start the application, it's calling that area route by default, although the user can't see anything and he gets an unauthorized page. Why is the application using the area route as the default route?
By saying {area=Admin} you are making the area part optional. So a route not containing an area will also be matched by that (with Admin as the chosen area).
If you want to make sure that only a path /Admin/ triggers your area, you could do it like this:
routes.MapRoute(
name: "admin",
template: "Admin/{controller=User}/{action=Index}/{id?}",
defaults: new { area = "Admin" });
You can also use this shortcut method which also sets up a route constraint for your area:
routes.MapAreaRoute("admin", "Admin",
"Admin/{controller=User}/{action=Index}/{id?}");
Also, the order in which you register your routes is also important. In general, the first route template that matches a route will be used. So since your admin route is rather specific, you should probably list that first, and only then fall back to a default route.
As the documentation on routing areas in MVC explains:
Conventional routing is order-dependent. In general, routes with areas should be placed earlier in the route table as they’re more specific than routes without an area.

How can I write a route that forces to a single controller/action?

I am trying to create a temporary website that basically locks it to display a single controller action.
I tried this but it didn't work:
routes.MapRoute(
name: "Test",
url: "Test/Index"
);
This is all I have in my RouteConfig.RegisterRoutes method other than:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
When I load the page I get:
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.
I think you are looking for
routes.MapRoute(
name: "Default",
url: "{*url}",
defaults: new { controller = "Test", action = "Index"});
Forces all requests to the TestController with the method Index.

URL routing in asp.net mvc

i have a ApplicationController class with an action called Admin
so my url is www.mysite.com/Application/Admin
is there anyway i can have the routing be www.mysite.com/Admin and go to this method.
i know i can do this by creating an AdminController but for this one function i thought it was easier to just put in another controller
Put this above your default route:
routes.MapRoute(
"ShortRoute",
"{action}",
new { controller = "Application", action = "Index"}
);
You can set the Application controller and the Admin method as the default controller and action, using parameter defaults:
routes.MapRoute(
"Default", // Route name
"{action}", // URL with parameters
new { controller = "Application", action = "Admin" }
);
If this is your last route, it will match any request that does not have a controller name and an action name in it. In this particular example, even a request without an action will execute your Admin action, since it's the default action.
Note that routes with parameter defaults can create strange behavior in your existing routes, if you have any. You can always use the ASP.NET MVC Routing Debugger to test which routes match a given URL.

Categories

Resources