How to use an Area in ASP.NET Core - asp.net-mvc-routing

How do I use an Area in ASP.NET Core?
I have an app that needs an Admin section. This section requires its Views to be placed in that area. All requests that start with Admin/ will need to be redirected to that area.

In order to include an Area in an ASP.NET Core app, first we need to include a conventional route in the Startup.cs file (It's best to place it before any non-area route):
In Startup.cs/Configure method:
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute", "{area:exists}/{controller=Admin}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Then make a folder named Areas in the app root and make another named Admin inside the former, also make these folders inside Admin (ViewComponent is optional):
Now we create a controller inside the Controllers folder named AdminController, the content can be like:
[Area("Admin")]
[Route("admin")]
public class AdminController : Controller
{
public AdminController()
{
// do stuff
}
public IActionResult Index()
{
return View();
}
[Route("[action]/{page:int?}")]
public IActionResult Orders()
{
return View();
}
[Route("[action]")]
public IActionResult Shop()
{
return View();
}
[Route("[action]/newest")]
public IActionResult Payments()
{
return View();
}
}
Now in order for that to work, you'll need to create Views for all actions that return one. The hierarchy for views is just like what you have in a non-area Views folder:
Now, you should be good to go!
Question:
What if I want to have another controller inside my Area?
Answer:
Just add another controller beside AdminController and make sure the routes are like the following:
[Area("Admin")]
[Route("admin/[controller]")]
public class ProductsController : Controller
{
public ProductsController()
{
//
}
[Route("{page:int?}")]
public IActionResult Index()
{
return View();
}
}
The important part is [Route("admin/[controller]")]. With that you can keep the style of routing to admin/controller/action/...

In ASP.NET Core 3.0. If you are working with Endpoint patterns, after adding the Area (Right click over project, Add, New Scaffolded Item, Area), you have to add manually routing pattern on startup.cs Configure method. (At this point the generated ScaffoldingReadMe.txt is out of date).
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(
"Admin",
"Admin",
"Admin/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

In the Microsoft docs to migrate from ASP.NET CORE 2.2 to 3.0 the suggestion is to:
Replace UseMvc with UseEndpoints.
I encountered some challenges while trying to fix my Area's while simultaneously having Identity to keep working - but the solution below seems to be working for ASP.NET CORE 3.0 :
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
Hopefully I could also help you out and reduce the research time :-)

Scaffolding has generated all the files and added the required dependencies.
However the Application's Startup code may required additional changes for things to work end to end.
Add the following code to the Configure method in your Application's Startup class if not already done:
app.UseMvc(routes =>
{
routes.MapRoute(
name : "areas",
template : "{area:exists}/{controller=Home}/{action=Index}/{id?}");
});

Areas Implementation in Routing
First Create Area(Admin) using VS and add the following code into Startup.cs
First Way to Implement:-
Add Controller Login and Index Action and add Following Code, [Area(“Admin”)] is compulsory to add on controller level to perform asp.net areas Routing.
Startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Login}/{action=Index}/{id?}"
);
});
Note: Area routing must be placed first with non area routing, area: exists is compulsory to add area routing.
Controller Code:
[Area("Admin")]
public class LoginController : Controller
{
public IActionResult Index()
{
return Content("Area Admin Login Controller and Index Action");
}
}
This route may be called using http://localhost:111/Admin
Second Way to Implement Area Routing:-
Add Following code into startup.cs.
app.UseMvc(routes =>
{
routes.MapAreaRoute(
name: "default",
areaName: "Guest",
template: "Guest/{controller}/{action}/{id?}",
defaults: new { controller = "GuestLogin", action = "Index" });
});
Create an Area “Guest”, Add “GuestLogin” Controller and “Index” Action and add the following code into the newly created controller.
[Area("Guest")]
public class GuestLoginController : Controller
{
public IActionResult Index()
{
return Content("Area Guest Login Controller and Index Action");
}
}
This route may be called using http://localhost:111/Guest

Use this pattern in Configure method in Startup.Cs, as its full routing manner:
app.UseMvc(routes =>{
routes.MapRoute(
name: "MyArea",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");});
In Core 3.1 you should use below code in ConfigureServices method:
services.AddMvc(option => option.EnableEndpointRouting = false);

With .net core, following is needed to be added in the startup file if you are adding an area:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
After that you can just simply mark your area and route in the controller, i.e
[Area("Order")]
[Route("order")]
it works for me.

Use this pattern in Configure method in Startup.Cs, as its full routing manner:
app.UseMvc(routes =>{
routes.MapRoute(
name: "MyArea",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");});
In Core 3.1 you should use below code in ConfigureServices method:
services.AddMvc(option => option.EnableEndpointRouting = false);

Related

WebApi HelpPage api detail page 404, when "api" prefix removed?

.net4.7 + WebApi5.23 + HelpPage5.23.
My WebApiConfig.Register:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}", //note: there is no "api/" prefix
defaults: new { id = RouteParameter.Optional }
);
}
}
And the index page is worked:
But the api detail page fail(Page not found):
Please help, thank you.
Routing is bound to be getting confused between routing to your MVC controller or your WebApi controller since the are now sharing the same path.
If you need a web page to show, create a new method within the HelpController that returns a new view.
If you need Json returned, you can still create a new method within the HelpController to do that, just change the return type to JsonResult.
Hopefully this gives you enough to understand what's going wrong, and therefore what to google next.

Web API routing and a Web API Help Page: how to avoid repeated entries

I am getting repeat entries rendered in my Web API Help Page with different parents, such as these, that refer to the same method:
GET api/{apiVersion}/v1/Products - Gets all products
...
GET api/v1/Products - Gets all products
...
I have a Web API page with some routing like this:
config.Routes.MapHttpRoute (
name: "DefaultVersionApi",
routeTemplate: "api/{apiVersion}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute (
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I had thought that this routing would make the "v1" optional, so the derived documentation above is not expected.
(sidebar: Going to api/products certainly doesn't work, so I am not sure what is wrong with this. What am I missing?)
It seems the real problem is that Web API Help Page is reading the routes improperly, as I thought v1 and {apiVersion} should not both appear in the same action. What am I missing here?
Try using Attribute Routing, install nuget package
Install-Package Microsoft.AspNet.WebApi.WebHost
Enable Attribute Routing in the WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Then use the attribute Route in the methods of your Controller
[Route("~/api/v1/Products")]
[HttpGet]
public List<Product> Products()
{}
[Route("~/api/v2/Products")]
[HttpGet]
public List<Product> V2Products()
{}
in the documentation you will get
GET api/v1/Products - Gets all products
GET api/v2/Products - Gets all products
It seems like this is a shortcoming of the ASP.NET Web API help pages. To workaround, I changed the view to exclude these invalid routes from the rendered document. For the above example, I added this Where clause to the loop in ApiGroup.cshtml, changing
#foreach (var api in Model){
to
#foreach (var api in Model.Where(m => !m.Route.RouteTemplate.Contains(#"{apiVersion}"))){

ASP.NET Web Api Routing Customization

I have WebApi controllers that end with the "Api" suffix in their names (For ex: StudentsApiController, InstructorsApiController). I do this to easily differentiate my MVC controllers from WebApi controllers. I want my WebApi routes to look similar to
http://localhost:50009/api/students/5 and not http://localhost:50009/api/studentsapi/5.
Currently to achieve this, I am setting up routes like
routes.MapHttpRoute(
name: "GetStudents",
routeTemplate: "api/students/{id}",
defaults: new { controller = "StudentsApi", id = RouteParameter.Optional });
routes.MapHttpRoute(
name: "GetInstructors",
routeTemplate: "api/instructors/{id}",
defaults: new { controller = "InstructorsApi", id = RouteParameter.Optional });
This is turning out to be very cumbersome as I have to add a route for each method in my controllers. I am hoping there should be an easy way to setup route templates that automatically adds the "api" suffix the controller name while processing routes.
Following #Youssef Moussaoui's direction I ended up writing the following code that solved the problem.
public class ApiControllerSelector : DefaultHttpControllerSelector
{
public ApiControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
}
public override string GetControllerName(HttpRequestMessage request)
{
if (request == null)
throw new ArgumentNullException("request");
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
return null;
// Look up controller in route data
object controllerName;
routeData.Values.TryGetValue("controller", out controllerName);
if (controllerName != null)
controllerName += "api";
return (string)controllerName;
}
}
And register it in Global.asax as
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector),
new ApiControllerSelector(GlobalConfiguration.Configuration));
Now that ASP.NET Web API 2 is out, there is a much less cumbersome way to do more complex routing like that you suggested, by using attribute routing.
At the top of your controller just add the following attribute:
[RoutePrefix("api/students")]
public class StudentsApiController : ApiController
{
...
}
And then before each API method:
[Route("{id}"]
public HttpResponseMessage Get(int id)
{
...
}
There is a bit of setup required, but the positives of doing routing this way are many. For one, you can put the routing with the controllers and methods that do the actual work, so you're never searching around wondering if you have the right route. Secondly and more importantly, it's much easier to do more complex routing, like having the controller name different from the route name (like you want) or having very complex patterns to match against.
I think the extensibility point you're looking for is the controller selector. You can create a class that derives from DefaultHttpControllerSelector and overrides the GetControllerName to strip out the "api" part. You can then register this controller selector on your service's configuration Services.
Following Youssef's comment on muruug's answer would look something like this
public class ApiControllerSelector : DefaultHttpControllerSelector
{
public ApiControllerSelector (HttpConfiguration configuration) : base(configuration) { }
public override string GetControllerName(HttpRequestMessage request)
{
return base.GetControllerName(request) + "api";
}
}

Return PartialView in MVC3 Area is not searching in area

I am working on an ASP.Net MVC 3 RC project. I have one area named Drivers. I have a LoadPartial() action in a controller in the Drivers area that returns a PartialView(string, object); When this is returned I get an error on my webpage that says "The partial view 'PublicAttendanceCode' was not found." It searched the following locations:
~/Views/AttendanceEvent/PublicAttendanceCode.aspx
~/Views/AttendanceEvent/PublicAttendanceCode.ascx
~/Views/Shared/PublicAttendanceCode.aspx
~/Views/Shared/PublicAttendanceCode.ascx
~/Views/AttendanceEvent/PublicAttendanceCode.cshtml
~/Views/AttendanceEvent/PublicAttendanceCode.vbhtml
~/Views/Shared/PublicAttendanceCode.cshtml
~/Views/Shared/PublicAttendanceCode.vbhtml
Why is it not searching in the Drivers Area?
I have the following pretty basic routes in Global.asax.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home",
action = "Index",
id = UrlParameter.Optional // Parameter defaults
}
);
}
And in DriversAreaRegistration.cs
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Drivers_default",
"Drivers/{controller}/{action}/{id}",
new { action = "RequestLeave", id = UrlParameter.Optional }
);
}
What am I missing that will make it look in the drivers area for the partial?
How are you providing area name to PartialView() method? I think you should be passing it in new { area = "Drivers" } as routeValues parameter.
The way that the MVC view engines know the area that they should look in is based on the route that was used to process the request.
In the case of the controller action that you have, are you certain that the request was processed by the area's route definition, or is it possible that the request was processed by the more general route that you defined in global.asax?
There are only four overloads of the method PartialView and it seems like neither of them accept routeValues as a parameter.
I solved this problem like this:
return PartialView(
VirtualPathUtility.ToAbsolute("~/Areas/MyArea/Views/Shared/MyView.cshtml"));
It works, but looks ugly.
This works too:
return PartialView("~/Areas/Admin/Views/Shared/MyView.cshtml", model);

Simple ASP.NET MVC views without writing a controller

We're building a site that will have very minimal code, it's mostly just going to be a bunch of static pages served up. I know over time that will change and we'll want to swap in more dynamic information, so I've decided to go ahead and build a web application using ASP.NET MVC2 and the Spark view engine. There will be a couple of controllers that will have to do actual work (like in the /products area), but most of it will be static.
I want my designer to be able to build and modify the site without having to ask me to write a new controller or route every time they decide to add or move a page. So if he wants to add a "http://example.com/News" page he can just create a "News" folder under Views and put an index.spark page within it. Then later if he decides he wants a /News/Community page, he can drop a community.spark file within that folder and have it work.
I'm able to have a view without a specific action by making my controllers override HandleUnknownAction, but I still have to create a controller for each of these folders. It seems silly to have to add an empty controller and recompile every time they decide to add an area to the site.
Is there any way to make this easier, so I only have to write a controller and recompile if there's actual logic to be done? Some sort of "master" controller that will handle any requests where there was no specific controller defined?
You will have to write a route mapping for actual controller/actions and make sure the default has index as an action and the id is "catchall" and this will do it!
public class MvcApplication : System.Web.HttpApplication {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "catchall" } // Parameter defaults
);
}
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new CatchallControllerFactory());
}
}
public class CatchallController : Controller
{
public string PageName { get; set; }
//
// GET: /Catchall/
public ActionResult Index()
{
return View(PageName);
}
}
public class CatchallControllerFactory : IControllerFactory {
#region IControllerFactory Members
public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName) {
if (requestContext.RouteData.Values["controller"].ToString() == "catchall") {
DefaultControllerFactory factory = new DefaultControllerFactory();
return factory.CreateController(requestContext, controllerName);
}
else {
CatchallController controller = new CatchallController();
controller.PageName = requestContext.RouteData.Values["action"].ToString();
return controller;
}
}
public void ReleaseController(IController controller) {
if (controller is IDisposable)
((IDisposable)controller).Dispose();
}
#endregion
}
This link might be help,
If you create cshtml in View\Public directory, It will appears on Web site with same name. I added also 404 page.
[HandleError]
public class PublicController : Controller
{
protected override void HandleUnknownAction(string actionName)
{
try
{
this.View(actionName).ExecuteResult(this.ControllerContext);
}
catch
{
this.View("404").ExecuteResult(this.ControllerContext);
}
}
}
Couldn't you create a separate controller for all the static pages and redirect everything (other than the actual controllers which do work) to it using MVC Routes, and include the path parameters? Then in that controller you could have logic to display the correct view based on the folder/path parameter sent to it by the routes.
Allthough I don't know the spark view engine handles things, does it have to compile the views? I'm really not sure.
Reflecting on Paul's answer. I'm not using any special view engines, but here is what I do:
1) Create a PublicController.cs.
// GET: /Public/
[AllowAnonymous]
public ActionResult Index(string name = "")
{
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
// check if view name requested is not found
if (result == null || result.View == null)
{
return new HttpNotFoundResult();
}
// otherwise just return the view
return View(name);
}
2) Then create a Public directory in the Views folder, and put all of your views there that you want to be public. I personally needed this because I never knew if the client wanted to create more pages without having to recompile the code.
3) Then modify RouteConfig.cs to redirect to the Public/Index action.
routes.MapRoute(
name: "Public",
url: "{name}.cshtml", // your name will be the name of the view in the Public folder
defaults: new { controller = "Public", action = "Index" }
);
4) Then just reference it from your views like this:
YourPublicPage <!-- and this will point to Public/YourPublicPage.cshtml because of the routing we set up in step 3 -->
Not sure if this is any better than using a factory pattern, but it seems to me the easiest to implement and to understand.
I think you can create your own controller factory that will always instantiate the same controller class.