繁体   English   中英

ASP.NET Core 3 MVC 路由参数不起作用

[英]ASP.NET Core 3 MVC Routing parameters not working

感觉我在这里做了一些愚蠢的事情,我在玩 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参数作为路由值正确通过。 无论 URL( /Main/Home/MyTeam还是/Main/Home?team=MyTeam ),以下配置每次都会给我一个404 其他情况要么给我上述问题,要么team参数出现null值..

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

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

你可以这样做:

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?}");
    });

暂无
暂无

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

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