gpt4 book ai didi

c# - 在 .Net Core 3.0 中替换 UseMvc

转载 作者:行者123 更新时间:2023-12-04 11:19:03 25 4
gpt4 key购买 nike

我想弄清楚如何正确替换 app.UseMvc()曾经是 .net core 2.2 一部分的代码。这些示例甚至告诉我我可以调用的所有代码是什么,但我还不明白我应该调用哪个。例如,对于我的 MVC Web 应用程序,我有以下内容:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStatusCodePagesWithReExecute("/Error/Index");
app.UseMiddleware<ExceptionHandler>();
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
context.Context.Response.GetTypedHeaders()
.CacheControl = new CacheControlHeaderValue
{
MaxAge = TimeSpan.FromDays(30)
};
}
});

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}

在我在 UseMvc() 中提供我的路由之前选项。但是现在看来我必须在 MapControllerRoute 内提供它但这些例子似乎也总是调用 MapRazorPages() .我需要调用两个还是我想只调用一个?两者之间的实际区别是什么,如何设置默认 Controller 和默认操作?

最佳答案

这记录在 Migrate from ASP.NET Core 2.2 to 3.0 中文章。假设您想要一个 MVC 应用程序。

The following example adds support for controllers, API-related features, and views, but not pages.


services
// more specific than AddMvc()
.AddControllersWithViews()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)

在配置中:
    public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();

app.UseRouting();

// The equivalent of 'app.UseMvcWithDefaultRoute()'
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
// Which is the same as the template
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}

有关使用顺序,请查看 documentation .

关于c# - 在 .Net Core 3.0 中替换 UseMvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58455770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com