首页 > 解决方案 > ASP.NET Core 3 MVC 路由参数不起作用

问题描述

感觉好像我在这里做一些愚蠢的事情,我在玩 ASP.NET Core 3 (MVC),做一些教程,熟悉 - 我在路由方面遇到了一些问题。

我在Startup.cs尝试设置Main/Home/{team}.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews(mvc => mvc.EnableEndpointRouting = true)
        .AddNewtonsoftJson(options =>
                        options.SerializerSettings.ContractResolver = new DefaultContractResolver()
        )
        .AddRazorRuntimeCompilation();
        services.AddKendo();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();

            endpoints.MapControllerRoute(
                name: "team",
                pattern: "Main/Home/{team}");

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

在我的Main控制器上。该动作Home有一个参数team

public class MainController : Controller
{
    private readonly ILogger<MainController> _logger;

    public MainController(ILogger<MainController> logger)
    {
        _logger = logger;
    }

    public IActionResult Home(string team)
    {

        TeamModel model = new TeamModel(team);
        return View(model);
    }
}

无论我做什么,我都无法将team参数作为路由值正确通过。下面的配置404每次都会给我一个,无论 URL (/Main/Home/MyTeam/Main/Home?team=MyTeam)。其他情况要么给我上述问题,要么team参数带有一个null值..

任何帮助都会很棒 - 我认为可能正在做一些愚蠢的事情!

标签: c#asp.net-coreasp.net-core-mvcasp.net-mvc-routing

解决方案


添加端点的方式没有将为此路由调用的控制器和操作。

你可以这样做:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();

    endpoints.MapControllerRoute(
        name: "team",
        pattern: "Main/Home/{team?}",
        defaults: new { controller = "Main", action = "Home" });

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

推荐阅读