gpt4 book ai didi

c# - 如何在 ASP.Net Core 1.1 中响应.Cookies.Append()?

转载 作者:行者123 更新时间:2023-11-30 19:23:57 26 4
gpt4 key购买 nike

我正在尝试将全局化添加到 Intranet 应用程序,使用 cookie 允许用户选择文化偏好。中间件已设置并正在运行,但我在根据 UI 选择附加到 cookie 时遇到了问题。

该方法直接来自 Asp.Net Core 文档,如下所示:

public void ConfigureServices(IServiceCollection services)
{
services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("en-GB"),
new CultureInfo("fr-FR"),
new CultureInfo("es-ES")
};

options.DefaultRequestCulture = new RequestCulture(culture: "en-GB", uiCulture: "en-GB");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});

services.AddLocalization();
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
})
.AddViewLocalization();

services.AddSession(options => {
options.CookieName = "Intranet";
});
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);

app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1)
});

return LocalRedirect(returnUrl);
}

问题是:

  1. 响应不存在
  2. 本地重定向不存在

我试过:

  1. HttpResponse、HttpRequest
  2. 本地重定向结果

最佳答案

从您获得该示例的文档中,您可以看到代码来自 GitHub有很多示例项目。此特定示例来自 Localization.StarterWeb .

你的两个“缺失”方法实际上是 ControllerBase 的一部分(这是 Controller 继承的。所以如果你把这个 Action 方法放到 Controller 中,它就会起作用.

public class HomeController : Controller
{
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);

return LocalRedirect(returnUrl);
}
}

关于c# - 如何在 ASP.Net Core 1.1 中响应.Cookies.Append()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978283/

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