Fork me on GitHub

AspNetCore不明确的匹配异常-请求与多个终结点匹配

框架:net 6.0 AspNet Core MVC

添加区域控制器HomeController,直接启动报错;

因默认路由下存在相同的控制器HomeController(非区域的),需要修改路由映射配置;

在Program.cs添加区域路由配置

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

完整代码如下:

using Microsoft.AspNetCore.Builder;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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.UseAuthorization();

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

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

app.Run();

区域路由添加到默认路由之后,如果添加到默认路由之前,默认首页将显示区域路由的默认控制器首页页面;

这里只是添加了区域路由,依然会报请求匹配多个路由端点,还需要在区域控制器HomeController上添加属性;

[Area("Admin")]
public class HomeController : Controller
{
    // ...
}

还可以添加`[Route("Admin/[controller]/[action]")]`属性,添加这个属性之后,区域下的页面访问比较死板,不够灵活。

 

posted @ 2023-09-27 11:11  chenpw  阅读(33)  评论(0编辑  收藏  举报
View Code