简体   繁体   中英

Web API and MVC in the same project with Session States

I'm been working around an ASP .Net MVC application that is going take log in requests from different sites with different configurations (so I cannot use the FormsAuthentication SSO way). The way I decided to resolve this was by creating temporal login request tokens, so each token could be used only once, and with those tokens, the application would make user session.

In order to avoid generating tokens unnecesarily, I thought of asking the server first if the user wasn't logged in already. And I decided to attempt this via HttpClient. The code is written as follows.

            var client = new HttpClient { BaseAddress = new Uri("http://mywidget.com") };
            client.Timeout = TimeSpan.FromMilliseconds(18000);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = client.GetAsync(String.Format("/userIsLogged/{0}", userId)).Result;
            response.EnsureSuccessStatusCode();
            bool isLogged = response.Content.ReadAsAsync<bool>().Result;
            return isLogged;

I came up with two possible ways to make the validation. I wrote the same action in Web API and in MVC as follows.

    [HttpGet]
    public bool UserIsLogged(int userId)
    {
        return (HttpContext.Current.Session != null && ((int)HttpContext.Current.Session["userId"]) == userId);
    }

With both I found problems, and I don't know which would server better for my purposes.

The MVC action returned the answer as HTML, and the client obviously couldn't handle the answer, and I haven't found yet a way to handle it correctly.

The API action could handles the answer, but Web API doesn't handle session states by default; you must tweak it so it can, and I don't know if both sessions are going to be the same.

I'm not sure which one of them is the right way to go, or if I should try another alternative to this problem.

Thank You.

The MVC actions should not return booleans. This does not necessarily mean you need to return a whole view object, thus querying the action will result into a full html, which is hard to parse.

You can force your action methods to return JSON or plain text. The type of the action is still ActionResult (it might be optionally JsonResult ), but you can return Json() or Content() .

For example:

public ActionResult UserIsLogged(int userId) 
{
    if (....)
    {
        return Json(true);
    }
    return Json(false); 
}

I would suggest also your Web API actions to return json aswell, instead of primitives. Will be easier for any client to parse the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM