Miguel Moura
Miguel Moura

Reputation: 39484

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?

Upvotes: 21

Views: 66069

Answers (1)

brad
brad

Reputation: 559

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

Upvotes: 40

Related Questions