Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create cookie with ASP.NET Core

In ASP.NET MVC 5 I had the following extension:

public static ActionResult Alert(this ActionResult result, String text) {
    HttpCookie cookie = new HttpCookie("alert") { Path = "/", Value = text };
    HttpContext.Current.Response.Cookies.Add(cookie);
    return result;
}

Basically I am adding a cookie with a text.

In ASP.NET Core I can't find a way to create the HttpCookie. Is this no longer possible?

like image 791
Miguel Moura Avatar asked Oct 25 '16 22:10

Miguel Moura


People also ask

What is cookie in ASP.NET Core?

Cookies are represented as key-value pairs, and you can take advantage of the keys to read, write, or delete cookies. ASP.NET Core uses cookies to maintain session state; the cookie that contains the session ID is sent to the client with each request.

Does ASP.NET Core identity use cookies?

You do not need a separate CookieAuthentication middleware when you are using ASPNET identity. UseIdentity() will do that for you and generate a cookie. You can set the "cookie options" in the AddIdentity block of the application like so: services.

How do I use cookie authentication in .NET Core?

Let's implement the Cookie Authentication in ASP.NET Core step by step. Open the Visual Studio and click on Create a new Project. Select ASP.NET Core Empty project and click on next. Give a name to your Project, select the location for the project creation, and click on Next.


1 Answers

Have you tried something like:

    public static ActionResult Alert(this ActionResult result, Microsoft.AspNetCore.Http.HttpResponse response, string text)
    {
        response.Cookies.Append(
            "alert",
            text,
            new Microsoft.AspNetCore.Http.CookieOptions()
            {
                Path = "/"
            }
        );

        return result;
    }

You may also have to pass the Response in your call to the extension method from the controller (or wherever you call it from). For example:

return Ok().Alert(Response, "Hi");

StackOverflow Reference

like image 99
brad Avatar answered Oct 09 '22 00:10

brad