Michael
Michael

Reputation: 13616

How to use Response property of controller class in static method?

I work on MVC5 project.

I have Login action method inside controller:

public void Login(LoginViewModel model, string returnUrl)
{
   string culture = getCulture();
   LocolizationCore.SetCulture(culture);
}

I have also in my project class named LocolizationCore and it contains static method named SetCulture().

Here how looks SetCulture() method:

    internal static void SetCulture(string culture)
    {
        // Validate input
        culture = CultureHelper.GetImplementedCulture(culture);

        // Save culture in a cookie
        HttpCookie cookie = Request.Cookies["_culture"];
        if (cookie != null)
            cookie.Value = culture;   // update cookie value
        else
        {
            cookie = new HttpCookie("_culture");
            cookie.Value = culture;
            cookie.Expires = DateTime.Now.AddYears(1);
        }
        Response.Cookies.Add(cookie);
    }

As you can see the SetCulture method is saving culture in user's cookies.

When I try to build the project I get error:

The name 'Request' does not exist in the current context    
The name 'Response' does not exist in the current context

My question is how to use Response and Request properties in static method of the LocolizationCore class?

Upvotes: 1

Views: 994

Answers (2)

Andrii Litvinov
Andrii Litvinov

Reputation: 13182

You can use HttpContext.Current.Request directly in your static class.

If you want to use an approach suggested by @Patrick Hofman you should wrap HttpContext.Current with HttpContextWrapper before passing it to the method:

SetCulture(new HttpContextWrapper(HttpContext.Current), "culture")

In the controller you have Request and Response properties. So I would suggest to pass those to your helper method.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156988

Pass in the HttpContext to your static method SetCulture:

internal static void SetCulture(HttpContextBase httpContext, string culture)
{
    // use httpContext.Request or httpContext.Response here
}

Pass it in like this:

SetCulture(this.HttpContext, "culture")

Or:

SetCulture(HttpContext.Current, "culture")

Upvotes: 4

Related Questions