asp.netCore3.0 中使用app.UseMvc() 配置路由

时间:2023-03-09 17:55:33
asp.netCore3.0 中使用app.UseMvc() 配置路由

一、新配置路由策略 

在 Asp.Net Core 3.0中默认不再支持app.UserMvc() 方式配置路由 系统。

而是使用新的模式,点击查看asp.netCore3.0区域和路由配置变化

默认使用的话 会抛出异常:

InvalidOperationException: Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. 
To use 'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices(...).

asp.netCore3.0 中使用app.UseMvc() 配置路由

二、Asp.Net Core 3.0中 对于app.UseMvc() 还是 支持的。

如果你 习惯了以前配置方式,还是可以使用的。

进需要在 配置服务 中 ConfigureServices  增加mvc支持,并且关闭终点路由。 EnableEndpointRouting=false .

示例代码如下:

public void ConfigureServices(IServiceCollection services)
{
//配置Mvc + json 序列化
services.AddMvc(options => { options.EnableEndpointRouting = false; })
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseAuthorization(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
}); //app.UseRouting();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
}

更多:

asp.netCore3.0区域和路由配置变化

在Asp.Net Core 3.0中如何使用 Newtonsoft.Json 库序列化数据

Asp.Net Core Cookie使用,Asp.net Core Cookie操作失效