简体   繁体   English

如何在 .net mvc 中更改 mvc controller 的区域?

[英]How to change area of mvc controller in .net mvc?

I have created new 'Admin' area , and i want to move there old two controllers with their views.( RoleManagerController, UserRolesController ) I tried to cut and paste all the files and it didnt work.我创建了新的“管理”区域,我想将旧的两个控制器及其视图移到那里。( RoleManagerController,UserRolesController )我试图剪切和粘贴所有文件,但它没有用。 Then i tried deleting old files and creating new controllers by clicking on ' add new controlle r' and creating new views by rigth clicking on controller methods and selecting 'Create view' , it didnt work as well.然后我尝试通过单击添加新控制器r”来删除旧文件并创建新控制器,并通过右击 controller 方法并选择“创建视图”来创建新视图,但它也不起作用。

Here is my project structure :这是我的项目结构

项目结构

I have moved two controllers: RoleManagerController , UserRolesController from ~/Controllers to ~/Areas/Admin/Controllers .我已将两个控制器: RoleManagerControllerUserRolesController~/Controllers移动到~/Areas/Admin/Controllers And their views from ~/Views to ~/Areas/Admin/Views .他们的观点从~/Views~/Areas/Admin/Views

When i try to access: localhost://Admin/RoleManager or localhost://Admin/UserRoles i get 404 HttpError :当我尝试访问: localhost://Admin/RoleManagerlocalhost://Admin/UserRoles我得到404 HttpError 管理员/用户角色 管理员/角色经理

If i try to acces their old routes: 'localhost://UserRoles' and 'localhost://RoleManager' i get next errors:如果我尝试访问他们的旧路线:'localhost://UserRoles' 和 'localhost://RoleManager' 我会收到下一个错误: 本地主机://用户角色 localhost://UserRoles(路由)

It seems that even thought i have deleted and created a new controllers in the new area, routing got unchanged.似乎即使我已经删除并在新区域中创建了一个新控制器,路由也没有改变。 here is my 'program.cs' file:这是我的“program.cs”文件:

using HotelReservationSystem.Data;
using HotelReservationSystem.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultUI()
    .AddDefaultTokenProviders();
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();


app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
      name: "Admin",
      pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    );
    app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
    app.MapRazorPages();

});

//Seeding user Roles and Default admin user
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    var loggerFactory = services.GetRequiredService<ILoggerFactory>();
    try
    {
        var context = services.GetRequiredService<ApplicationDbContext>();
        var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
        await ContextSeed.SeedRolesAsync(userManager, roleManager);
        await ContextSeed.SeedSuperAdminAsync(userManager, roleManager);
    }
    catch (Exception ex)
    {
        var logger = loggerFactory.CreateLogger<Program>();
        logger.LogError(ex, "An error occurred seeding the DB.");
    }
}

app.Run();

/Areas/Admin/Controllers/RoleManagerController.cs /Areas/Admin/Controllers/RoleManagerController.cs

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace HotelReservationSystem.Areas.Admin.Controllers
{
    public class RoleManagerController : Controller
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        public RoleManagerController(RoleManager<IdentityRole> roleManager)
        {
            _roleManager = roleManager;
        }
        public async Task<IActionResult> Index()
        {
            var roles = await _roleManager.Roles.ToListAsync();
            return View(roles);
        }
        [HttpPost]
        public async Task<IActionResult> AddRole(string roleName)
        {
            if (roleName != null)
            {
                await _roleManager.CreateAsync(new IdentityRole(roleName.Trim()));
            }
            return RedirectToAction("Index");
        }
    }
}

/Areas/Admin/Views/RoleManager/index.cshtml : /Areas/Admin/Views/RoleManager/index.cshtml

    ViewData["Title"] = "Role Manager";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Менеджер ролей</h1>
<form method="post" asp-action="AddRole" asp-controller="RoleManager">
    <div class="input-group">
        <input name="roleName" class="form-control w-25">
        <span class="input-group-btn">
            <button class="btn btn-primary">Добавить новую роль</button>
        </span>
    </div>
</form>
<table class="table table-striped">
    <thead>
        <tr>
            <th>Id</th>
            <th>Роль</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var role in Model)
        {
            <tr>
                <td>@role.Id</td>
                <td>@role.Name</td>
            </tr>
        }
    </tbody>
</table>

You have to add Area attribute on top of your controller class to associate the controller with the area.您必须在 controller class 顶部添加区域属性,以将 controller 与该区域相关联。 Eg例如

[Area("RoleManager")]
public class RoleManagerController : Controller
{
}

For more detail refer: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-6.0有关更多详细信息,请参阅: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-6.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM