0

what I want to do is using HttpContext.Session in the API

in the same WebApi Controller but different actions.

$.ajax({
url:baseAppUrl+"api/login",
type:"post",
data:{
action:"sms",
username:"",///mobile phone
},
success:function(ret,err){

}

it will give me a code and then use the code to login.

but after the ajax send the reqeust again I can not get the HttpContext.Session.

I am using .net core 3.1

if (action.Equals("sms"))
        {
            if (string.IsNullOrEmpty(username))
            {
                return Json(new { Ok = false, Message = "parameter is null" });
            }
            Random rnd = new Random();
            var verifyCode = rnd.Next(111111, 999999).ToString();
            HttpContext.Session.SetString("code", verifyCode);
            return Json(new { Ok = true, Message = verifyCode });
        }

and in the login action:

if (action.Equals("mobileLogin"))
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(code))
            {
                return Json(new { Ok = false, Message = "paremeter is null" });
            }
            var userCode = HttpContext.Session.GetString("code"); //the userCode will be null.
            if (!string.IsNullOrEmpty(userCode))
            {
                ////.....
            }
}

but with the postman all is worked.

why?

1
  • Could you post here also the code of the controller action please? Which version of .NET Core are you using? Commented Mar 26, 2020 at 7:46

1 Answer 1

0

In Startup.cs, make sure the following is added to ConfigureServices and Configure methods

public void ConfigureServices(IServiceCollection services)  
{
    ...  
    services.AddSession(options => {  
        options.IdleTimeout = TimeSpan.FromMinutes(20);//You can set Time   
    });
    ...  
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseSession();
    ...
}

Please, also check that the browser receives the session cookie. In Chrome:

  1. click in the lock icon in URL bar
  2. click Cookies
  3. see if there is a cookie .AspNetCore.Session, as in the following picture

enter image description here

If the cookie is there, the problem is probably not in handling session data but somewhere else.

Sign up to request clarification or add additional context in comments.

3 Comments

It is working in developpment but not work in the iis.
modified the answer
Could you also please try run the app in a different browser and in the anonymous mode?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.