Search code examples
c#asp.netstatic-methodshttpcontext

How to write a cookie inside a static method


i need to write a cookie inside static method (i need static because i want to call this method from others classes). I found solution with HttpContex.Current, but it is not work for me. I get this error

An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.HttpContext.get'

I also tried add using System.Web.HttpContext.Current; and i get this error

'System.Web.HttpContext.Current' is a 'property' but is used like a 'type'

My method:

public static void WriteCookie(Guid token)
{ 
    HttpCookie cookie = new HttpCookie("LoginControl");

    cookie.Value = token.ToString();
    cookie.Expires = DateTime.Now.AddHours(0.5);

    HttpContext.Current.Reponse.Cookies.Add(cookie);
}

Any suggestions? Thank a lot Mathew.


Solution

  • Can you pass the HttpContext using the method parameter?

    public static void WriteCookie(HttpContext context, Guid token)
    { 
        HttpCookie cookie = new HttpCookie("LoginControl");
    
        cookie.Value = token.ToString();
        cookie.Expires = DateTime.Now.AddHours(0.5);
    
        context.Response.Cookies.Add(cookie);
    }