Reputation: 463
I used the default method to create an area. Right-click on project and add a new scaffolded item. Selected area, gave it a name and it created the folder structure.
My area is called Login
. I created a controller (in the Areas/Login/Controllers
folder) called AccountController
with a method called Login
that does nothing but return view();
.
In my HomeController
I added an [Authorize]
attribute and the only action is the default index.
I have my routes setup:
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(name: "login",
pattern: "{area:exists}/{controller=Account}/{action=Login}/{id?}");
endpoints.MapControllerRoute(name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
I tested with a break point and I am correctly hitting the AccountController > Login action inside the area, but when it returns the view it does not find the view Areas/Login/Views/Account/Login.cshtml
.
It's actually looking in the main site. If I add a Login.cshtml
file inside the main site's Views/Shared
folder it will load it.
I feel like I'm missing a configuration step somewhere in the program.cs
file but I don't know what it would be. Like Identity is not looking in the right spot, or I have to specify it's in an area. Help me Obi-wan.
Upvotes: 3
Views: 5202
Reputation: 463
I figured it out myself. This is what worked to create an identity redirect into an Area with my own custom controller/path/view instead of using the asp.net core built in magical identity pages.
Add an endpoint in program.cs to map the route.
endpoints.MapAreaControllerRoute(
name: "Buffoon",
areaName: "Buffoon",
pattern: "Buffoon/{controller=Account}/{action=Login}");
Create the Area in your code; Right click on the Website, select Add > New Scaffolded item, Select Area, Input Area Name.
Add your controller and view in the area to match with your route defaults.
Tag your controller inside your area with [Area("Area_Name")]
. In my example above I would have used [Area("Buffoon")]
In the builder configuration area of your program.cs file set the login path variable inside the application cookie. Using my example above;
builder.Services.ConfigureApplicationCookie(cke => { cke.LoginPath = "/Buffoon/Account/Login"; });
User
is a custom class inheriting from IdentityUser
and MyDbContext
is my custom EF context inheriting from IdentityDbContext<User>
).
builder.Services.AddIdentity<User, IdentityRole>(cfg => { cfg.User.RequireUniqueEmail = true; }).AddEntityFrameworkStores<MyDbContext>();
Ensure you have added app.UseAuthentication();
and app.UseAuthorization();
to your application configuration section of the program.cs file.
Lastly I put an [Authorize]
attribute on my default route home controller and upon hitting that, the redirect happened into my newly created Area and displayed my login view.
Upvotes: 2