I am using the following code for sign in in a web api. I get null reference exception on FormsAuthentication.SetAuthCookie(authUser.UserId.ToString(), false);
call. Please guide me what I am doing wrong...
[AllowAnonymous]
[HttpPost]
public async Task<string> SignIn(JObject credentails)
{
string returnVal = "";
await Task.Run(() =>
{
string userName = (string)credentails.SelectToken("Username");
string password = (string)credentails.SelectToken("Password");
UserService userSvc = new UserService(new SqlConnection(_conStr));
var authUser = userSvc.Authenticate(userName, password);
if (authUser != null)
{
FormsAuthentication.SetAuthCookie(userName, false);
HttpContext.Current.Session.Add("DR_CLIENT_ID", authUser.DRClientId);
HttpContext.Current.Session.Add("USER_ID", authUser.UserId);
returnVal = authUser.FullName;
}
else
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Invalid Credentials!"),
ReasonPhrase = "Error"
});
}
});
return returnVal;
}
UPDATE-1 in this case no value is actually null as I can see it in the debug mode. but when I remove wait Task.Run(() = {}); block from this code, it works fine without any issue.