nvcnvn
nvcnvn

Reputation: 5175

ASP.NET MVC - Access Cookies data in non-Controller class

I need to write a function that help me do something in some of my Controllers so I decided to creat a class called Helper for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace HocVuiDiary.Helper
{
    public class CookiesHelper
    {
        public void UpdateSubkey(string name, string subkey, string subvalue)
        {
            HttpCookie cookie;
            if (Request.Cookies[name] == null)
            {
                cookie = new HttpCookie(name);
                cookie[subkey] = subvalue;
            }
            else
            {
                cookie = Request.Cookies[name];
                cookie[subkey] = subvalue;
            }
            cookie.Expires = DateTime.Now.AddDays(30);
            Response.Cookies.Add(cookie);
        }
    }
}

The issue is I cannot Access to Request or Response any more!
PLease show me the right way!

Upvotes: 3

Views: 8273

Answers (3)

Jenn
Jenn

Reputation: 902

While the first answer is technically accurate, I am running into issues of inconsistency with creation of the cookie using an external .DLL. The code behind class calls the methods in the external .dll, the cookie is created, but after navigating to the next page the cookie does not exist, sometimes.

    public void CreateCookie(string cookieName, string key, string value)
    {
        int minutes = 95;
        string encryptedValue = utilities.EncryptString(value);
        HttpCookie cookie = new HttpCookie(cookieName);
        cookie[key] = encryptedValue;
        cookie.Expires = DateTime.Now.AddMinutes(minutes);
        HttpContext.Current.Response.Cookies.Add(cookie);
    }

Other calls to the external class are working as expected.

    public bool CheckCookieExists(string cookieName)
    {
        bool exists = true;
        HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
        if (cookie != null)
        {
            return exists;
        }
        return exists = false;
    }

Upvotes: 3

Adam Tuliper
Adam Tuliper

Reputation: 30152

It's basically the same as accessing the session. Use httpcontext.current although it is frowned upon at times there is mention here of cleaning it up: Can I use ASP.NET Session[] variable in an external DLL

Here you could define an interface like IRequest to abstract the specific implementation out but that's up to you.

Upvotes: 0

Wouter de Kort
Wouter de Kort

Reputation: 39898

You can use HttpContext.Current.Request and HttpContext.Current.Response in your helper class.

Upvotes: 9

Related Questions