Niranjan Godbole
Niranjan Godbole

Reputation: 2175

How to set and return session id in headers in web api2

After successful login I want to return session_id in response headers and along with that some object I want to return.

My typical response header is as follows.

Response
Header: Set-cookie: session_id=121212-343dsfsd-4323132, path=/, expires: 1212
Body: {
    “status”: 0,
    “data”: {
        “userRole”: “SUPER_ADMIN”
    }
}

I am trying as below to achieve above.

bool result = //...validate username and password with database

if(result == true)
{
    SessionIDManager manager = new SessionIDManager();
    string newSessionId= manager.CreateSessionID(HttpContext.Current);
    var resp = new HttpResponseMessage();
    var cookie = new CookieHeaderValue("session-id",newSessionId);
    cookie.Expires = DateTimeOffset.Now.AddDays(1);
    cookie.Domain = Request.RequestUri.Host;
    cookie.Path = "/";
    resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
    //return resp;
    obj.UserRole = (from c in entityObject.NCT_UserRegistration where obj.User_Name == c.User_Name && obj.User_Password == c.User_Password select c.User_Role).FirstOrDefault();
    obj.Success = 0;
    obj.User_Password="";
    return Ok(obj);
}

I am not sure the way I followed correct or not. How can I return sessionid as above?

Upvotes: 1

Views: 2494

Answers (1)

Nkosi
Nkosi

Reputation: 247058

Refactor the above code as follows

if(result == true) {

    obj.UserRole = (from c in entityObject.NCT_UserRegistration where obj.User_Name == c.User_Name && obj.User_Password == c.User_Password select c.User_Role).FirstOrDefault();
    obj.Success = 0;
    obj.User_Password = "";

    var response = Request.CreateResponse(HttpStatusCode.OK, obj);

    var newSessionId = new SessionIDManager().CreateSessionID(HttpContext.Current);
    var cookie = new CookieHeaderValue("session-id", newSessionId);
    cookie.Expires = DateTimeOffset.Now.AddDays(1);
    cookie.Domain = Request.RequestUri.Host;
    cookie.Path = "/";

    response.Headers.AddCookies(new[] { cookie });

    return ResponseMessage(response);
}

Main difference is how the response is created and returned. The original code was creating a new response manually, populating it with cookie and then returning another completely different response that had the body minus cookie. ie: Ok(obj).

The above code creates a response that includes the object value to be returned and then the cookie header information is added to the response.

If the original intention of the OP was to return IHttpActionResult, then ResponseMessage(response) will wrap the HttpResponseMessage in a IHttpActionResult derived implementation.

Upvotes: 1

Related Questions