我在我的ASP.NET Core MVC应用程序中有一个Admin区域,当我试图达到/Admin/Category/Add时,它说No webpage was found的网址:https://localhost:7002/Category/Add?area=Admin.

我的路由在program.cs:

app.MapDefaultControllerRoute();

app.MapAreaControllerRoute(
        name: "Admin",
        areaName: "Admin",
        pattern: "Admin/{controller=Home}/{action=Index}/{id?}"
        );

我的看法:

@model List<Category>

@{
    ViewData["Title"] = "Index";
    Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}

<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-body">

                <a asp-area="Admin" asp-controller="Category" asp-action="Update" class="btn mb-1 btn-primary">Add Category</a>

                <div class="card-title">
                    <h4>Table Basic</h4>
                </div>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Created By</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var item in Model)
                            {
                                <tr>
                                    <td>@item.Name</td>
                                    <td>@item.CreatedBy</td>
                                    <td>@item.IsDeleted</td>
                                    <td>
                                        <a asp-area="Admin" asp-controller="Category" asp-action="Update" asp-route-id="@item.Id">
                                            <button type="button" class="btn mb-1 btn-warning">Update</button>
                                        </a>
                                        <a asp-area="Admin" asp-controller="Category" asp-action="Delete" asp-route-id="@item.Id">
                                            <button type="button" class="btn mb-1 btn-danger">Delete</button>
                                        </a>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

我的控制器:

namespace AnimeUI.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class CategoryController : Controller
    {
        private readonly ICategoryService categoryService;
        private readonly IValidator<Category> validator;
        private readonly IMapper mapper;

        public CategoryController(ICategoryService categoryService, IValidator<Category> validator, IMapper mapper)
        {
            this.categoryService = categoryService;
            this.validator = validator;
            this.mapper = mapper;
        }

        public async Task<IActionResult> Index()
        {
            var categories = await categoryService.GetAllCategoriesNonDeletedAsync();

            return View(categories);
        }

        [HttpGet]
        public IActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Add(AddCategoryDto addCategoryDto)
        {
            var category = mapper.Map<Category>(addCategoryDto);
            var result = validator.Validate(category);
            var exists = await categoryService.Exists(category);

            if (exists)
                result.Errors.Add(new ValidationFailure("Name", "This category name already exists"));

            if (result.IsValid)
            {
                await categoryService.CreateCategoryAsync(addCategoryDto);
                return RedirectToAction("Index", "Category", new { Area = "Admin" });
            }

            result.AddToModelState(this.ModelState);

            return View(addCategoryDto);
        }
    }
}

我一直在寻找一整天,但不能找到一个有效的解决这个恼人的问题.出于某种原因,我的URL是这样生成的:

https://localhost:7002/Category/Add?area=Admin

而不是

https://localhost:7002/Admin/Category/Add

我试着改变我的端口,添加不同的路由语法.我目前正在使用Visual Studio 2022,我的项目是. NET 8.0

PS:我的问题只发生在我需要go Admin页的时候.

推荐答案

我建议在创建/使用区域时遵循官方文档中描述的步骤:Areas in ASP.NET Core

当按照文档并添加一个区域时,您会看到以下ScaffoldingReadMe.txt个:

Scaffolding has generated all the files and added the required dependencies.

However the Application's Startup code may require 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.UseEndpoints(endpoints =>
    {
      endpoints.MapControllerRoute(
        name : "areas",
        pattern : "{area:exists}/{controller=Home}/{action=Index}/{id?}"
      );
    });

这正是使路由过程正确工作的目的.在您的情况下,使用以下代码:

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
      name: "areas",
      pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    );

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

上述图案areas是通用的,并且也将用于其它区域.

不要忘记使用正确的Area folder structure.


By the way, you code is working good for me. Therefore, I suppose your problem is caused by incorrect folders structure: use 100 menu command from the 101 folder. The Visual Studio template will help you to avoid mistakes.

Csharp相关问答推荐

从C#网站调用时找不到存储过程

MongoDB实体框架核心:表达必须可写

禁用AutoSuggestBox项目更改时的动画?

O(N)测试失败

有没有一种方法可以在包含混合文本的标签中嵌入超链接?

如何模拟耐久任务客户端在统一测试和获取错误在调度NewsListationInstanceAsync模拟设置

选取器与.NET Maui MVVM的绑定属性

更新产品但丢失产品ASP.NET Core的形象

不带身份的Blazor服务器.Net 8 Cookie身份验证

我如何让我的秒表保持运行场景而不重置

Azure函数-在外部启动类中生成配置时出错

为什么我的伺服电机不动,下面的代码?

Postgres ENUM类型在第一次运行时对Dapper不可见

如何在使用属性 Select 器时判断是否可以为空

为什么在使用JsonDerivedType序列化泛型时缺少$type?

工厂类是如何在.NET 8中注册的?

Foreach非常慢的C#

Xamarin.Forms-如何创建可 Select 的显示alert 或弹出窗口?

如何解决System.StackOverflowException:抛出System.StackOverflowException类型的异常.&# 39;生成随机代码时发生异常?

为什么我的UserControl没有加载到我的主窗口中?