c# - .net core 3 , MVC , Using 'UseMvcWithDefaultRoute' to configure MVC is not supported while using Endpoint Routing
问题描述
我正在尝试创建一个基于 ASP.NET Core 3 的简单项目。
ASP.NET Core 2.2 的 MVC 模板在启动类中有以下行:
app.UseMvcWithDefaultRoute();
此行在 ASP.NET Core 2.2 中完美运行,并且路由工作,但是,在 ASP.NET Core 3.0 中它无法编译并显示以下错误
使用端点路由时不支持使用“UseMvcWithDefaultRoutee”配置 MVC。
问题是:“如何在 .net core 版本 3 中为 MVC 应用程序配置路由?”
解决方案
我在以下官方文档“从 ASP.NET Core 2.2 迁移到 3.0 ”中找到了解决方案:
有3种方法:
- 禁用端点路由。
(add in Startup.cs)
services.AddMvc(option => option.EnableEndpointRouting = false)
或者
- 将 UseMvc 或 UseSignalR 替换为 UseEndpoints。
就我而言,结果看起来像这样
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
}
}
或者
- 使用 AddControllers() 和 UseEndpoints()
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
推荐阅读
- mysql - 在 directus 无头 cms 中执行存储过程
- reactjs - 在 React 中第二次单击时,按钮功能不起作用
- c++ - 使用 boost 光纤实现的单个生产者、多个并行消费者
- c++ - 我将如何创建一个构造函数来从自定义 String 类初始化一个字符?
- post - 从使用 Google Apps 脚本登录的 Google 帐户发送 POST 请求
- react-native - 使用带有 Firebase 身份验证的 react-native-google-signin(android 实现)
- javascript - Promise.all 的异步图像预加载在非 Chrome 浏览器上不起作用
- python - 如何将 Python 2.7 字符串解释为 C char 数组中的整数?
- reactjs - 将 event.target.value 作为参数发送到已调度的操作
- python - Pip 将文件安装到旧版本的 Python(Pip、Pandas、Python、Mac)