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

I am trying to add Globalization to an Intranet application, using a cookie to allow users a culture preference. The middleware is set up and running but I have run into an issue with appending to the cookie based on the UI selection.

The method is straight from the Asp.Net Core documentation as below:

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

The issues are:

  1. Response does not exist
  2. LocalRedirect does not exist

I have tried:

  1. HttpResponse, HttpRequest
  2. LocalRedirectResult

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

ASP.NET Core Working With Cookie, ASP.NET Core Working With Cookie. This article explains how ASP. In ASP.​NET, we can access cookies using httpcontext.current but in ASP. Append(key, value, option);; } public void Remove(string key); {; Response. public IActionResult Index(); {; //read cookie from IHttpContextAccessor; string  HttpContext.Response.Cookies.Append( "name", "value", new CookieOptions() { SameSite = SameSiteMode.Lax }); All ASP.NET Core components that emit cookies override the preceding defaults with settings appropriate for their scenarios. The overridden preceding default values haven't changed.

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.

HttpResponse.Cookies Property (System.Web), Gets the response cookie collection. ASP.NET includes two intrinsic cookie collections. The collection accessed through the Cookies collection of HttpRequest  ASP.NET Core Working With Cookie. This article explains how ASP.NET Core deals with cookies. Cookies are key-value pair collections where we can read, write and delete using key. HTTP Cookie is some piece of data which is stored in the user&#39;s browser.

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

HttpResponse.Cookies Property (Microsoft.AspNetCore.Http , Gets an object that can be used to manage cookies for this response. Cookies Property. Definition. Namespace: Microsoft.AspNetCore.Http Http.​IResponseCookies Cookies { get; } Applies to. ASP.NET Core. 3.1 3.0 2.2 2.1 2.0 1.1 1.0  Read and Write Cookies in ASP.NET Core 1.0. One of the basic requirements in several web applications is storing and retrieving small pieces of information in cookies. This article will discuss with an instance how ASP.NET Core 1.0 deals with cookies. You will learn here to read and write cookies using ASP.NET Core.

Cookies and Consent in ASP .NET Core, This is the third of a new series of posts on ASP . NET Core web app, you should see a cookie popup that appears on every page that can be you to store the user's “No” response in the cookie itself, thus going against their wishes. UseCookiePolicy() in the Configure() method of your Startup.cs file. 10 things to know about in-memory caching in ASP.NET Core: Consume ASP.NET Core Web API using HttpClient: Offline installation of VS2017 in 4 Easy Steps: Read and Write Cookies in ASP.NET Core 1.0: Form, Query String and HttpContext in ASP.NET Core 1.0: Seed Users and Roles Data in ASP.NET Core Identity: Use Razor Pages, MVC, and Web API in a

Consider adding a version of Response.Cookies.Append that does , It is specially useful for backward compatibility with ASP.NET (not Core) where cookies were not encoded automatically by the framework and  I am still battling with setting cookies in asp.net core sighing for the simplicity of php at times setcookie() wishing for it in asp.net core – Max Apr 14 '17 at 7:47 1 This is not an answer, it is a status update.

Using Cookie Middleware without ASP.NET Core Identity, AspNetCore.Authentication.Cookies package. Then add the following lines to the Configure method in your Startup.cs file before the app.UseMvc() statement;. Closed 8 months ago. I have a simple ASP.NET Core 2.1 application which is supposed to set and then read a cookie. Whenever I try to read the cookie it returns null. Looking further in the browser's inspect tool I am unable to find it. I came up with this small implementation to see if I can sort out whats going on, but it is not working..

Comments
  • Do you have that code inside a controller or is it standalone somewhere else?
  • Possible duplicate of Cookies and ASP.NET Core
  • Controller ... not class. That was a silly mistake, thank you so much!
  • Great timing. Just starting work on a new app in 2.1, perhaps 2.2 soon and will be coming across this shortly I would imagine.
  • This doesn't answer the question at all.
  • And how does the code you've provided allow the user to switch culture preferences?
  • The code which I provided is showing the configuration which I'm using to use exactly the same action as was in the question. I've also mention in the first paragraph that "...the action you have in the example should works just fine..." if the configuration will be correct.
  • Thanks for posting that code. I have updated my question to include my startup elements. I am not localizing in anyway so have no .resx files to include but I think we are very similar. It is interesting that you are using Microsoft.AspNetCore.Localization.RequestCulture() for default though.