everyone.
my sessions work correctly when I use it locally, but when in deploy on the server this error occurred :
Object reference not set to an instance of an object
I deploy very simply project but it does not work again
public ActionResult Index()
{
Session["name"] = "javad bayat";
ViewBag.Message = Session["name"].ToString();
return View();
}
public ActionResult About()
{
try
{
ViewBag.Message = Session["name"].ToString();
}
catch (Exception w)
{
ViewBag.Message = w.Message;
}
return View();
}
do I have to check the windows server or config my web.config to sth else?
thanks for your help
Related
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?
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 need to pass one logout successful message in one of the views but I am not able to do so. Here is what I have.
Not Working Solution:
//LogController:
public ActionResult Logoff()
{
DoLogOff();
TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
// HomeController
public ActionResult Index()
{
return View();
}
Index CSHTML File:
#Html.Partial("../Home/DisplayPreview")
DisplayPreview CSHTML File:
#TempData["Message"]
Working Solution
public ActionResult Logoff()
{
DoLogOff();
return RedirectToAction("Index", "Home", new { message = "Logout Successful!" });
}
public ActionResult Index(string message)
{
if (!string.IsNullOrEmpty(message))
TempData["Message"] = message;
return View();
}
Index CSHTML File:
#TempData["Message"]
But I want something like my first solution.
In the controller;
public ActionResult Index()
{
ViewBag.Message = TempData["Message"];
return View();
}
public ActionResult Logoff()
{
DoLogOff();
TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
Then you can use it in view like;
#ViewBag.Message
See if this works:
public ActionResult Logoff()
{
DoLogOff();
ControllerContext.Controller.TempData["Message"] = "Success";
return RedirectToAction("Index", "Home");
}
Since you don't show what DoLogOff() does, my guess is that you are abandoning the session, which means any data stored in session (like TempData) is lost. A new session does not get generated until the next page refresh, so it doesn't work.
What you might try is simply passing a flag to your Index view that will show the logged off message if it's present. I would NOT use the string message, like you show in your "working" example, because this can be coopted by attackers to redirect people to malicious sites.
hi i want to share my version
public ActionResult List(string success,string error)
{
TempData["success"] = success;
TempData["error"] = error;
return View();
}
public ActionResult Add()
{
return RedirectToAction("List",new
{
error = "not added",
success = "added"
});
}
Hi people I have the following code (shown below) and I am trying to change it (its my code) so i can display a message box or some alert saying the book has been saved using an if statement in C# ASP.net MVC3
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(BooksItem booksitem)
{
try
{
using (var db = new Booksforsale())
{
db.BooksItem.Add(booksitem);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Is there a way to change this to an If statement so when its saved a message box or an alert appears saying it has been saved. I would like real simple coding nothing to complex that will be hard for me to implement.
Thank You
I have tried the following:
[HttpPost]
[ValidateInput(false)]
If public ActionResult Create(BooksItem booksitem)
{
try
{
if using (var db = new Booksforsale())
{
db.BooksItem.Add(booksitem);
db.SaveChanges();
}
else viewbag.message="been added"
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
This has not worked thank you so much people for any help received really appreciate it thanks
You could store the message inside TempData so that it is available on the next request after you redirect:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(BooksItem booksitem)
{
try
{
using (var db = new Booksforsale())
{
db.BooksItem.Add(booksitem);
db.SaveChanges();
}
TempData["message"] = "The item has been saved";
return RedirectToAction("Index");
}
catch
{
return View();
}
}
and inside the Index action that you are redirecting to fetch the message from TempData and pass it to the view:
public ActionResult Index()
{
ViewBag.Message = TempData["message"];
return View();
}
and obviously display this message somewhere in the corresponding view:
<div>#ViewBag.Message</div>
I've recently created an ASP.NET MVC 2 application, which works perfectly in the development environment. However, when I deploy it to the server (123-reg Premium Hosting), I can access all of the expected areas - except the Account controller (www.host.info/Account). This then attempts to redirect to the Error.aspx page (www.host.info/Shared/Error.aspx) which it cannot find. I've checked that all of the views have been published, and they're all in the correct place.
It seems bizarre that two other controllers can be accessed with no problems, whereas the Account controller cannot be found. I have since renamed the AccountController to SecureController, and all of the dependencies, to no avail.
The problem with not being able to find the Error.aspx page also occurs on the development environment.
Any ideas would be greatly appreciated.
Thanks,
Chris
1) Can you check the DLL that was published to make sure that type exists in the assembly? Are any special modifiers applied to the Account controller compared to the other controllers (such as specific attributes, base classes, additional code)?
2) Can you verify what HttpMethod you are using to request the page? I'm assuming just a normal GET, but it may be coming in as a different verb causing you not to find your action method.
3) Are you using any custom routing, or just the standard {controller}/{action}/{id} setup?
The version of IIS on the server is 7.0, of which I have no control over.
The account controller code all works perfectly on the development environment, and the code is as follows:
[HandleError]
public class SecureController : Controller
{
private UserManager manager;
public IFormsAuthenticationService FormsService { get; set; }
public IMembershipService MembershipService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
// Lazy man's Dependency Injection for now, use Ninject later!
public SecureController(UserManager mgr) { manager = mgr; }
public SecureController() : this(new UserManager(new PortfolioDataDataContext())) { }
// **************************************
// URL: /Account/LogOn
// **************************************
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
// **************************************
// URL: /Account/LogOff
// **************************************
public ActionResult LogOff()
{
FormsService.SignOut();
return RedirectToAction("Index", "Home");
}
// **************************************
// URL: /Account/Register
// **************************************
public ActionResult Register()
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View();
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus = manager.CreateUser(model.UserName, model.Password, model.Email, model.FullName);
if (createStatus == MembershipCreateStatus.Success)
{
FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View(model);
}
// **************************************
// URL: /Account/ChangePassword
// **************************************
[Authorize]
public ActionResult ChangePassword()
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View();
}
[Authorize]
[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
if (ModelState.IsValid)
{
if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
{
return RedirectToAction("ChangePasswordSuccess");
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
// If we got this far, something failed, redisplay form
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View(model);
}
// **************************************
// URL: /Account/ChangePasswordSuccess
// **************************************
public ActionResult ChangePasswordSuccess()
{
return View();
}
}