c# - 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
值..
任何帮助都会很棒 - 我认为可能正在做一些愚蠢的事情!
解决方案
添加端点的方式没有将为此路由调用的控制器和操作。
你可以这样做:
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?}");
});
推荐阅读
- javascript - 收到响应后在角度(5)中更改 responseType
- mysql - MySql 查询从两个表中获取结果
- vba - 如何从 Excel VBA 获取总体规划中的 MSP 子项目状态日期
- oracle - ODP.NET 能否通过实体框架工具支持 LDAP?
- selenium - 如何将 LeanFT Selenium 与 HP QC 集成
- firebase - Cloud Firestore 规则时间戳
- javascript - 使用 chai-http 使用 mocha-chai 进行测试期间的 UnhandledPromiseRejectionWarning
- java - 不使用 final 关键字我们可以避免继承吗?
- reactjs - 有什么方法可以知道子组件是否已安装在 React 中
- active-directory - 通过域外的 SAM 帐户名获取 UPN?