C# 如何获取Startup.cs';什么是配置方法?
我有一个多语言网站,是我编写的ASP.NET Core 3.1 MVC it支持两种语言:阿塞拜疆语和英语。它使用路由库本地化 我为使用异常页面设置了C# 如何获取Startup.cs';什么是配置方法?,c#,asp.net-core,model-view-controller,C#,Asp.net Core,Model View Controller,我有一个多语言网站,是我编写的ASP.NET Core 3.1 MVC it支持两种语言:阿塞拜疆语和英语。它使用路由库本地化 我为使用异常页面设置了app.UseExceptionHandler(…),如下所示 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionP
app.UseExceptionHandler(…)
,如下所示
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/en/main/error");
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/en/main/error", "?code={0}");
...
}
但我有一个问题。问题是我的例外页面总是使用“en”
区域性
因为我设置了app.UseExceptionHandler的errorEandlingPath的硬代码。(app.UseExceptionHandler(“/en/main/error”);
和app.useStatusCodePageSwithExecute(“/en/main/error”,“?code={0}”);
)
我的站点的路由配置如下所示:
...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{culture=az}/{controller=Main}/{action=Index}/{id?}");
}
...
如何在app.UseExceptionHandler(“/en/main/error”)中动态设置当前区域性代码>
例如:如果用户使用阿塞拜疆文化,errorEandlingPath必须是“/az/main/error”
,否则“/en/main/error”
我试过了
app.UseExceptionHandler(“/{culture}/main/error”)代码>
及
app.UseStatusCodePagesWithReExecute(“/{culture}/main/error”,“?code={0}”)代码>
但两者都不起作用。请帮帮我,谢谢)你要做的是一个中间件,让我们称之为例外HTMLHandler
,你必须从标题中获得“接受语言”
,才能知道他来自何方。
如果要返回404/403/etc,则需要根据异常进行控制
这是中间件:
public class ExceptionHtmlHandler
{
private readonly RequestDelegate _next;
public ExceptionHtmlHandler(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (YourException e)
{
context.RequestServices
.GetService<ILogger>()
.Error(e);
PersonalizedMethod1(context, e);
}
catch (Exception e)
{
context.RequestServices
.GetService<ILogger>()
.Error(e);
HandleException(context, e);
}
}
private static void PersonalizedMethod1(HttpContext context, Exception e)
{
var lang = context.Request.Headers["Accept-Language"];
var errorCode = HttpStatusCode.BadRequest;
context.Response.StatusCode =(int)errorCode;
context.Response.Redirect($"/{lang}/main/error/{errorCode}");
}
// other errors
private static void HandleException(HttpContext context, Exception e)
{
context.Response.Redirect("/error");
}
}
嗨,我的朋友。谢谢你的主意。我试试你们的代码,你们用的是“接受语言”的标题。但在我的代码中,头的“Accept Language”是空的,所以我检查context.Request.Path中是否有dedect区域性。我最终决定,基于UseStatusCodePagesWithReExecute重写自己的中间件。我将检查UseStatusCodePagesWithReExecute或ExceptionHandlerMiddleware-的源代码。它对我有用。谢谢你的主意
[HttpGet("{lang}/main/error/{errorCode}")]
public async Task<ViewResult> Error(string lang,int errorCode )
{
return View("Error", await GetErrorTranslated(lang,errorCode ));
}