18

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?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • 2
    Possible duplicate of [Cookies in ASP.NET Core rc2](http://stackoverflow.com/questions/37958343/cookies-in-asp-net-core-rc2) – adem caglin Oct 26 '16 at 06:41
  • Possible duplicate of [Cookies and ASP.NET Core](https://stackoverflow.com/questions/36166075/cookies-and-asp-net-core) – Michael Freidgeim Sep 27 '17 at 08:01
  • If you need to support multiple values per cookie, you can check this out: https://stackoverflow.com/questions/43701126/how-to-handle-multi-value-cookies-in-asp-net-core – Francisco Goldenstein Jul 20 '18 at 14:59

1 Answers1

37

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

Community
  • 1
  • 1
brad
  • 529
  • 4
  • 5