The login user name can be obtained from the User property of ControllerBase, RazorPageBase and PageModel such like string? name = User.Identity?.Name;
if he is authenticated. But I don't know the "usertype". What is it?
How to pass values from a Razor page to an Asp.Net MVC controller
I am working on an Asp.Net Core MVC project. The identity was scaffolded and uses Razor pages. When the user enters the username and password, if they are valid, they will be redirected to an MVC controller where they have to answer a security question. For that, I have to pass two variables, username and usertype, from the Login.cshtml page to the controller. The following is my code. Although it works, it uses TempData to pass values. Even the older WebForms had methods such as Request.Form collection to send values from one page to another. Is there a better way to pass values from a Razor page to a controller?
public async Task<IActionResult> SecurityQuestionSetup()
{
var userName = TempData["username"]?.ToString();
var userType = TempData["usertype"]?.ToString();
if (!string.IsNullOrEmpty(userType) && userType.Equals("E"))
{
userType = "EXECUTIVE";
userName = $"{userType}{userName}";
}
else if (!string.IsNullOrEmpty(userType) && userType.Equals("m"))
{
userType = "MANAGERIAL";
userName = $"{userType}{userName}";
}
var securityQuestionList = await _saveSecurityQuestion.GetSecurityQuestionsAsync();
SecurityQuestionVM securityQuestionVM = new()
{
SecurityQuestionsList = securityQuestionList.Select(s => new SelectListItem
{
Text = s.SecurityQuestion,
Value = s.SecurityQuestionID.ToString(),
})
};
3 answers
Sort by: Most helpful
-
SurferOnWww 3,066 Reputation points
2024-05-07T04:14:52.1333333+00:00 -
AgaveJoe 28,456 Reputation points
2024-05-07T10:30:01.4833333+00:00 You are using Identity. The username is available in every request after a successful authentication.
User.Identity.Name
The userType should be a stored as user claim in the Identity database. Take advantage of the UserManger() api to set the user claim.
var user = await _userManager.GetUserAsync(User); await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("userType", "E"));
Once the claim is assigned to the user then the claim can be fetched from the User principal after a successful authentication.
User.Claims.FirstOrDefault(t => t.Type == "userType").Value
Creating a claims policy simplifies authorization process.
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-8.0
-
Bruce (SqlWork.com) 66,056 Reputation points
2024-05-07T15:38:21.9833333+00:00 TempData uses a cookie to pass the data. you can also just pass on the redirect url query string, but you should encrypt the data. another option is store data in a keyed persistent store and pass the key.
and finally you could create an instance of the controller and call the method directly.