Session Value is not correct - asp.net-mvc

I have 2 tables, User and RolesDetail
and
I want to store Session["role"] from RolesDetail but when i stored the value is System.Data.Entity.DynamicProxies.....
I want to store session with value from joined table
public ActionResult Login(User u)
{
var user = db.Users.SingleOrDefault(a => a.Username == u.Username && a.Password == u.Password);
if (this.IsCaptchaValid("Captcha Is Not Valid !!"))
{
if (user != null)
{
Session["role"] = user.RolesDetail.Roles;
Session["user"] = user.Username;
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Username or Password is Wrong !!");
}
}
ViewBag.ErrMessage = "Error: Captcha Is Not Valid !!";
return View();
}
Session["user"] work just fine

Related

REST API check if email exists

I would like to check if the user exists with the email in the database. I want to do this in the API, it should simply return true or false. This is what i get; when the user exists it returns true if the user does not exist in DB it returns a 500 internal server error. How could I solve this? Thanks in advance
public IHttpActionResult GetUserEmail(string Email)
{
var User = (db.Users
.Where(p => p.Email == Email)
.First());
if (User == null)
{
return Ok(false);
}
else
{
return Ok(true);
}
}
The answer has been given above, I am leaving an example code block just as an example. :)
var User = db.Users.FirstOrDefault(p => p.Email == Email);
if (User == null)
{
return Ok(false);
}
else
{
return Ok(true);
}
// or
var User = db.Users.Any(p => p.Email == Email);
if (!User)
{
return Ok(false);
}
else
{
return Ok(true);
}
code block with the changes as mentioned by #Dawood Awan in the comments –
public IHttpActionResult GetUserEmail(string Email)
{
var User = (db.Users
.Where(p => p.Email == Email)
.FirstOrDefault());
if (User == null)
{
return Ok(false);
}
else
{
return Ok(true);
}
}

How to deal with a non existing session variable?

I am trying to check if a booking record exists, then show its details. Otherwise return to Bookparking page but else part isn't working and shows Object reference not set to an instance of an object because there is no such field with the Session[""]
Controller:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"].ToString();
ViewBag.userid = id;
var checkbooking = db.tb_booking.Where(s => s.username == id).FirstOrDefault();
if (checkbooking != null)
{
var show = db.tb_booking.Where(e => e.username == id).FirstOrDefault();
}
else
{ //ViewBag.f = "You have no booking yet!!";
return RedirectToAction("Bookparking", "user");
}
return View();
}
}
As Gabriel noted, you have not null checked the value from the session. Code would be something like this:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"]?.ToString();
if (id != null)
{
ViewBag.userid = id;
var checkbooking = db.tb_booking.FirstOrDefault(s => s.username == id);
if (checkbooking != null)
{ // TODO: checkbooking is currently unused, except to check if you can fetch it.
return View();
}
}
// If you reach this code, then either id is null, or the booking was not found
return RedirectToAction("Bookparking", "user");
}
}

Compare user input values with values in database in asp.net mvc

Heading ##[HttpPost]
public ActionResult LogIn(UserDetail user)
{
using (AdventureWorksDBEntities User = new AdventureWorksDBEntities())
{
var UserInput= User.UserDetails.Where(b => b.UserName == user.UserName && b.Password == user.Password).FirstOrDefault();
if (UserInput!=null)
{
Session["Id"] = UserInput.id.ToString();
Session["UserName"] = UserInput.UserName.ToString();
return Redirect("#");
}
else
{
ModelState.AddModelError("","Username or Password Doesn't Exist");
}
}
return View();
I want to compare user input values with the values in the database.

Simple custom register/login system how to hash and retrieve password

I have created a simple register/login system and right now when the user registers it just stores their plain password in the database. I am wondering how I can hash it then when they login, how do I unhash it and compare it to what they put in.
All I have in my users table/model class is username and password
UsersController
// GET: Register User
public ActionResult Register(User user)
{
if (ModelState.IsValid)
{
using (UserContext db = new UserContext())
{
db.Users.Add(user);
db.SaveChanges();
}
ModelState.Clear();
}
return View();
}
// POST: Login User
[HttpPost]
public ActionResult Login(User user)
{
using (UserContext db = new UserContext())
{
var usr = db.Users.SingleOrDefault(u => u.Username == user.Username && u.Password == user.Password);
if (usr != null)
{
Session["UserID"] = usr.Username.ToString();
return RedirectToAction("Index", "Profile");
}
else
{
ModelState.AddModelError("", "Username or Password Incorrect");
}
}
return View();
}

Insert data into database(MVC)

I am trying to insert datas to Appointment table of my database. I did registration part of my project which works well. There are 2 tables, Patient and Appointment. After Login patients can make an appointment. Patient number comes like this
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
For appointment date and description comes from textbox. And I want to insert PatientNo from Patient table to Appointment table. For me it looks done but when I choose date and write description but I got error on this line app.PatientNo = patient.PatientNo;
An exception of type 'System.NullReferenceException' occurred in DentAppSys.dll but was not handled in user code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Make(Models.AppModel User)
{
if (Session["UserEmail"] != null)
{
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var app = new Appointment();
app.Date = User.Date;
app.Description = User.Description;
app.Status = "true";
app.PatientNo = patient.PatientNo;
db.Appointments.InsertOnSubmit(app);
db.SubmitChanges();
return RedirectToAction("Make", "Appointment");
}
}
else
{
return RedirectToAction("Index", "User");
}
}
}
}
and this is registration part which is working well
public ActionResult RegAndLogin(Models.RegAndLog User)
{
if (User.RegisterModel != null)
{
if (ModelState.IsValid)
{
using (var db = new MaindbModelDataContext())
{
var Person = db.Patients.FirstOrDefault(u => u.Email == User.RegisterModel.Email);
if (Person == null)
{
string Hash = BCrypt.Net.BCrypt.HashPassword(User.RegisterModel.Password);
var MyUser = new Patient();
MyUser.Name = User.RegisterModel.Firstname;
MyUser.Surname = User.RegisterModel.Lastname;
MyUser.Birthday = User.RegisterModel.Birthday;
MyUser.Email = User.RegisterModel.Email;
MyUser.Password = Hash;
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
db.Patients.InsertOnSubmit(MyUser);
db.SubmitChanges();
Session["UserEmail"] = User.RegisterModel.Email;
return RedirectToAction("Index", "Patient", User.RegisterModel);
}
else
{
ModelState.AddModelError("", "There is a user with this Email. Please enter another Email !!!");
return View();
}
}
}
else
{
ModelState.AddModelError("", "Data is incorrect !!!");
}
}
else
{
if (ModelState.IsValid && IsValid(User.LoginModel.Email, User.LoginModel.Password))
{
var TempUser = new Models.RegisterModel();
Session["UserEmail"] = User.LoginModel.Email;
using (var db = new MaindbModelDataContext())
{
var person = db.Patients.FirstOrDefault(u => u.Email == User.LoginModel.Email);
TempUser.Firstname = person.Name;
TempUser.Lastname = person.Surname;
//TempUser.RegisterModel.Birthday = (DateTime)person.BirthDate;
TempUser.Email = person.Email;
}
return RedirectToAction("Index", "Patient", TempUser);
}
else
{
ModelState.AddModelError("", "Check your E-mail or Password then try again !!!");
}
}
return View();
If you're getting a null exception on the line
app.PatientNo = patient.PatientNo;
It will be because either app or patient are null at when it's executed. I would suspect patient.
Check that patient is found correctly at the line
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
if it isn't found patient will be null.

Resources