Accessing Session Using ASP.NET Web API

前端 未结 13 969
谎友^
谎友^ 2020-11-22 04:32

I realize session and REST don\'t exactly go hand in hand but is it not possible to access session state using the new Web API? HttpContext.Current.Session is a

13条回答
  •  攒了一身酷
    2020-11-22 05:16

    Mark, if you check the nerddinner MVC example the logic is pretty much the same.

    You only need to retrieve the cookie and set it in the current session.

    Global.asax.cs

    public override void Init()
    {
        this.AuthenticateRequest += new EventHandler(WebApiApplication_AuthenticateRequest);
        base.Init();
    }
    
    void WebApiApplication_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
    
        SampleIdentity id = new SampleIdentity(ticket);
        GenericPrincipal prin = new GenericPrincipal(id, null); 
    
        HttpContext.Current.User = prin;
    }
    
    enter code here
    

    You'll have to define your "SampleIdentity" class, which you can borrow from the nerddinner project.

提交回复
热议问题