Currently, I am working on a web application using MVC C#. I would like to ask if there is a way to implement a PHP Session in MVC. The use of the session I am talking about is like, when you write only the link or path like this from https://localhost:44360/Login/Login to https://localhost:44360/Home/Home to go to the Home Page of the Web even if you did not sign-in using an account you will not be redirected to that page.
After I logged in to an account, I am redirected to the homepage which is correct, after that, I logged out the account and try to Type https://localhost:44360/Home/Home and unfortunately it was redirected or even clicking the back button of the browser.
I am currently working on the code below.
LoginController.cs
[HttpPost]
public ActionResult Login(LoginModel userInfo, FormCollection collection, string returnUrl)
{
ILogicInterface<LogicalUserInput, LogicalSystemResult> iLogic = new UserLoginCheck();
LogicalUserInput userInput = new LogicalUserInput();
_ = new LogicalSystemResult();
try
{
userInput[typeof(LoginModel).FullName] = userInfo;
LogicalSystemResult systemResult = iLogic.DoProcess(userInput);
bool userCheckExist = systemResult.ResultCode != LogicalSystemResult.RESULT_CODE_ERR_DATA_NOT_EXIST;
if (userCheckExist)
{
UserLoginModel loginModel = systemResult[typeof(UserLoginModel).FullName] as UserLoginModel;
Session["userInfo"] = loginModel;
FormsAuthentication.SetAuthCookie(loginModel.email, true);
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
if (loginModel.AccountType == 0) {
return RedirectToAction("Home", "Home");
} else {
return RedirectToAction("Error", "Error");
}
}
}
else
{
TempData.Clear();
TempData["Title"] = "Error!";
TempData["Message"] = " Invalid Username Or Password.";
return View();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return RedirectToAction("Error", "Error");
}
}
Logout Button in HOME.cshtml
<a id="cmdLogOff">
<i class="feather icon-log-out"></i>Logout
</a>
Click Event of LogoutButton
<script>
$("#cmdLogOff").on("click", function () {
$("#HomeView").submit();
});
</script>
#using (Ajax.BeginForm("LogOut",
null,
new AjaxOptions
{
},
new { id = "HomeView" }))
{
}
HOMEController.cs
[Authorize]
public ActionResult Home()
{
if (Session["userInfo"] == null) {
return RedirectToAction("Error", "Error");
} else {
UserLoginModel userLoginModel = Session["userInfo"] as UserLoginModel;
TempData["user"] = userLoginModel.lastName + ", " + userLoginModel.firstName + " " + userLoginModel.middleName;
return View();
}
}
[Authorize]
[HttpPost]
public ActionResult LogOut() {
try {
Session.Abandon();
FormsAuthentication.SignOut();
Session["userInfo"] = null;
return RedirectToAction("Login", "Login");
} catch (Exception ex) {
Console.WriteLine(ex.Message);
return View();
}
}
The main question here is that, how can I not redirect the user if he/she just only type the link he/she wants to access without an account. And after logging out of an account, the Home Page will not be shown even if the user clicked the back of the browser?
Related
Result Image
When I run my project I see that regular expressions like [Required] is checked before entering any data and submitting.
Is anyone here able to help?
public ActionResult Add(Student stdnt)
{
if (ModelState.IsValid == true)
{
BlStudent Bl = new BlStudent();
if (Bl.Add(stdnt) == true)
{
ViewBag.message = "Successfully Added!";
}
else
{
ViewBag.message = "Unsuccessful to Add";
}
}
else
{
ViewBag.message = "Please enter the information correctly!";
}
return View();
}
I could solve this problem by using [HTTPPOST] and [HTTPGET]! Now the regular expressions are not checked on loading. Just as you send the data to the server by clicking the button, it happens.
this is on load:
and this is after sending to the server:
[HttpPost]
public ActionResult Add(Student stdnt)
{
if (ModelState.IsValid == true)
{
BlStudent Bl = new BlStudent();
if (Bl.Add(stdnt) == true)
{
ViewBag.message = "Successfully Added!";
}
else
{
ViewBag.message = "Unsuccessful to Add";
}
}
else
{
ViewBag.message = "Please enter the information correctly!";
}
return View();
}
[HttpGet]
public ActionResult Add()
{
return View();
}
I have a problem with ASP.Net MVC regarding authentication. The user managed to login and log out with no problem but when I click the back button is in the browser on the watch still logged in !!!
Can someone help me!!!
I also remind you that I am not using the default authentication of Visual Studio
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var isValidUser = IsValidUser(model);
if(isValidUser != null)
{
FormsAuthentication.SetAuthCookie(model.UserMail, true);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("Eror", "Invalid login attempt");
return View();
}
}
else
{
return View(model);
}
}
public User IsValidUser(LoginViewModel model)
{
using(var db = new DbCaimanContext())
{
User user = db.Users.Where(q => q.UserMail.Equals(model.UserMail) && q.Password.Equals(model.Password)).SingleOrDefault();
if (user == null)
return null;
else
return user;
}
}
And here is my disconnection method :
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
Session.Abandon();
return RedirectToAction("Login");
}
In your Login Get Method
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
if (HttpContext.User.Identity.IsAuthenticated)
return RedirectToAction("Index", "Main");// go to anywhere you want
else
return View();
}
I am working on a MVC Web App which is calling a Web API. In my Create (POST) method, a user will enter email addresses of some users in the database. I have a check to enter the email only if the email does not already exist in the database or not. If it already exists, I want to be able to show an error message to the user "Email already exists".
I don't know how to handle the response to display an error message to the user when it fails to create an approveduser? I am trying with a try-catch case, but it is not working. I have ViewBag.Message = error which I am trying to display in my Index View when it fails. But nothing is displaying. When I debug, it doesn't even go to the catch when the email exists in the database, it just takes me to the Index view.
public ActionResult Create([Bind(Include = "Email,FirstName,LastName")] ApprovedUsers approvedUsers)
{
try
{
using (WebClient client = new WebClient())
{
token = Session.GetDataFromSession<string>("access_token");
client.Headers.Add("authorization", "Bearer " + token);
byte[] response = client.UploadValues(apiUrl, "POST", new NameValueCollection()
{
{ "Email", approvedUsers.Email },
{ "FirstName",approvedUsers.FirstName },
{ "LastName",approvedUsers.LastName }
});
string result = System.Text.Encoding.UTF8.GetString(response);
return RedirectToAction("Index");
}
}
catch
{
return RedirectToAction("Index", new { error = "Email exists" });
}
}
Index Action
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, string error)
{
ViewBag.Message = error;
This is the API method being called.
public IHttpActionResult PostApprovedUsers(ApprovedUsers approvedUsers)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!db.ApprovedUsers.Any(u => u.Email == approvedUsers.Email))
{
db.ApprovedUsers.Add(approvedUsers);
db.SaveChanges();
}
return CreatedAtRoute("DefaultApi", new { id = approvedUsers.Email }, approvedUsers);
Try this:
public ActionResult Create([Bind(Include = "Email,FirstName,LastName")] ApprovedUsers approvedUsers)
{
try
{
using (WebClient client = new WebClient())
{
token = Session.GetDataFromSession<string>("access_token");
client.Headers.Add("authorization", "Bearer " + token);
byte[] response = client.UploadValues(apiUrl, "POST", new NameValueCollection()
{
{ "Email", approvedUsers.Email },
{ "FirstName",approvedUsers.FirstName },
{ "LastName",approvedUsers.LastName }
});
string result = System.Text.Encoding.UTF8.GetString(response);
}
}
catch
{
TempData["Error"] = "Email Exists";});
}
RedirectToAction("Index");
}
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, string error)
{
ViewBag.Message = TempData["Error"].ToString();
}
It was my API that was causing the issue. Even when it failed to create the duplicate email, it never went to the catch because I didn't have a bad request return if the email did exist in the database.
Changed my API to this and then it was working.
if (db.ApprovedUsers.Any(u => u.Email == approvedUsers.Email))
{
return Content(HttpStatusCode.BadRequest, "Email exists already");
}
else
{
db.ApprovedUsers.Add(approvedUsers);
}
try
{
db.SaveChanges();
}
catch (DbUpdateException e)
{
if (ApprovedUsersExists(approvedUsers.Id))
{
return Conflict();
}
throw e;
I have a problem starting a new asp.net application. I choose asp.net mvc template with Individual User Accounts authentication and project generates and starts normally. My question is: what do i have to do to use register/login options? From what I understood methods responsible for these actions are generated automatically, but should I do something about database schema for information about users (shoudn't it be created also automatically?).
Anyway, after filling fields in register form i get error that a file couldn't be found and the error is found on line 155: var result = await UserManager.CreateAsync(user, model.Password);
I'm using Visual Studio Community 2015 on windows 8. Thank you in advance
public async Task<IActionResult> Register(RegisterVM registerVM)
{
if (!ModelState.IsValid)
{
return View();
}
AppUser appUser = new AppUser()
{
Fullname = registerVM.Fullname,
UserName = registerVM.Username,
Email = registerVM.Email
};
IdentityResult result = await _userManager.CreateAsync(appUser, registerVM.Password);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View(registerVM);
}
await _userManager.AddToRoleAsync(appUser, Roless.Admin.ToString());
await _signInManager.SignInAsync(appUser, true);
return RedirectToAction("index", "home");
}
public IActionResult Login()
{
return View();
}
[HttpPost]
[AutoValidateAntiforgeryToken]
public async Task<IActionResult> Login(LoginVM loginVM, string returnurl)
{
if (!ModelState.IsValid)
{
return View();
}
AppUser dbUser = await _userManager.FindByEmailAsync(loginVM.Email);
if (dbUser == null)
{
ModelState.AddModelError("", "Ya email ya da Password sehvdir");
return View(loginVM);
}
SignInResult result = await _signInManager.PasswordSignInAsync(dbUser, loginVM.Password, loginVM.RememerMe, true);
if (result.IsLockedOut)
{
ModelState.AddModelError("", "Your Account Is Lock Out");
return View(loginVM);
}
if (!result.Succeeded)
{
ModelState.AddModelError("", "Ya Email ya da Password sehvdir");
return View(loginVM);
}
if (returnurl == null)
{
return RedirectToAction("index", "home");
}
foreach (var item in await _userManager.GetRolesAsync(dbUser))
{
if (item.Contains(Roless.Admin.ToString()))
{
return RedirectToAction("index", "Dashboard", new { area = "AdminF" });
}
}
return Redirect(returnurl);
}
I'm creating ASP.NET MVC 4 Internet Application.
In that Application I created Login Page that any user can log in to, then I allowed to redirect user to different pages based on their role.
ASP.NET Identity is the membership system here.
This is my Login Controller method:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
if (user.ConfirmedEmail == true)
{
await SignInAsync(user, model.RememberMe);
if (String.IsNullOrEmpty(returnUrl))
{
if (UserManager.IsInRole(user.Id, "HEC_Admin"))
{
return RedirectToAction("Index", "HEC");
}
//role Admin go to Admin page
if (UserManager.IsInRole(user.Id, "HEI_User"))
{
return RedirectToAction("Index", "HEI");
}
}
else
{
return RedirectToLocal(returnUrl);
}
}
else
{
ModelState.AddModelError("", "Confirm Email Address.");
}
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
This is HEI Controller Class:
public class HEIController : Controller
{
//
// GET: /HEI/
[Authorize(Roles = "HEI_User")]
public ActionResult Index()
{
return View();
}
}
This is my HEC Controller Class:
public class HECController : Controller
{
//
// GET: /HEC/
[Authorize(Roles = "HEC_Admin")]
public ActionResult Index()
{
return View();
}
}
when I remove [Authorize(Roles = "HEC_Admin")] above the index action in HECController class and when I remove [Authorize(Roles = "HEC_User")] above the index action in HEIController class this is working fine,
but then How restrict unauthorized access to these pages?
I had the same problem as you and I still don't know the reason why it happens. What I did was to create my own custom Authorization Attribute and check the Roles myself.
public class CustomAuthorizationAttribute : AuthorizeAttribute
{
public string IdentityRoles
{
get { return _identityRoles ?? String.Empty; }
set
{
_identityRoles = value;
_identityRolesSplit = SplitString(value);
}
}
private string _identityRoles;
private string[] _identityRolesSplit = new string[0];
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//do the base class AuthorizeCore first
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
if (_identityRolesSplit.Length > 0)
{
//get the UserManager
using(var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
var id = HttpContext.Current.User.Identity.GetUserId();
//get the Roles for this user
var roles = um.GetRoles(id);
//if the at least one of the Roles of the User is in the IdentityRoles list return true
if (_identityRolesSplit.Any(roles.Contains))
{
return true;
}
}
return false;
}
else
{
return true;
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//if the user is not logged in use the deafult HandleUnauthorizedRequest and redirect to the login page
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
//if the user is logged in but is trying to access a page he/she doesn't have the right for show the access denied page
{
filterContext.Result = new RedirectResult("/AccessDenied");
}
}
protected static string[] SplitString(string original)
{
if (String.IsNullOrEmpty(original))
{
return new string[0];
}
var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}
I also added the HandleUnauthorizedRequest method to redirect to a appropriated page if the user has is logged in but has no access to this action or controller
To use it just do this:
[CustomAuthorization(IdentityRoles = "HEI_User")]
public ActionResult Index()
{
return View();
}
Hope it helps.