开发者

Asp.net mvc FormsAuthentication from a service

开发者 https://www.devze.com 2023-02-03 21:27 出处:网络
I\'m looking at the nerddinner code and in their AuthenticationC开发者_运维技巧ontroller, they have the following code:

I'm looking at the nerddinner code and in their AuthenticationC开发者_运维技巧ontroller, they have the following code:

        if (String.IsNullOrEmpty(alias)) throw new ArgumentException("Value cannot be null or empty.", "alias");

        FormsAuthenticationTicket authTicket = new
            FormsAuthenticationTicket(1, //version
            userdId.ToString(), // user name
            DateTime.Now,             //creation
            DateTime.Now.AddMinutes(30), //Expiration
            createPersistentCookie, //Persistent
            alias); //since Classic logins don't have a "Friendly Name"

        string encTicket = FormsAuthentication.Encrypt(authTicket);
        this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

My problem is that I want to move this code into a class that does not inherits from the Controller type. The problem with this is the last line of code where it sets the cookie; Response, which is specific to Controller.

How do I set encTicket to a cookie without having access to the controller? Is there a way to use FormsAuthentication class itself to d this?


You could have a method in your separate class which returns the cookie so that the only thing the controller has to do is add the cookie to the response. IMO cookie management (adding/deleting) is the responsibility of the controller:

var cookie = authService.CreateAuthCookie(userId, alias);
Response.AppendCookie(cookie);


This is how to add the encrypted ticket to the browser cookie without using a controller.

    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
                     {
                         Expires = authTicket.Expiration,
                         Path = FormsAuthentication.FormsCookiePath
                     };

    if (HttpContext.Current != null)
    {
        HttpContext.Current.Response.Cookies.Add(cookie);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消