How to Response.Cookies.Append() in ASP.Net Core 1.1?

烂漫一生 提交于 2019-12-02 00:52:05

From the docs where you got that sample, you can see that the code comes from GitHub with lots of sample projects. This particular sample comes from Localization.StarterWeb.

Your two "missing" methods are actually part of ControllerBase (which is what Controller inherits from. So if you put this action method into a controller, it will work.

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);
    }
}

In ASP .NET Core 2.1+, if you use the cookie policy feature for implementing GDPR by invoking app.UseCookiePolicy() in Startup.cs, make sure to mark your cookie as essential, otherwise it won't be sent to users who haven't accepted your policy.

Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions 
            { 
                Expires = DateTimeOffset.UtcNow.AddYears(1), 
                IsEssential = true 
            }
        );

Obviously, you should also mention the cookie in your privacy statement.

First of all you've to use CookieRequestCultureProvider. Later one the action you have in the example should works just fine. I would also add this:

CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;

Here is my config:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

    services.AddMvc()
        .AddViewLocalization(
            Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.SubFolder,
            opts => { opts.ResourcesPath = "Resources"; }
        )
        .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(opts =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"), 
            ...               
        };
        opts.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US");
        opts.SupportedCultures = supportedCultures;
        opts.SupportedUICultures = supportedCultures;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseRequestLocalization();

    app.UseMvc(routes =>
    {
        routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}");
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!