I'm creating a MVC 4 application, I had error like following.
I tried lot of things but I can't find what is the problem.here is my Controller source
public ActionResult Index(string EventId)
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["User"];
if (cookie != null)
{
string Type = (cookie["Type"] == null || cookie["Type"] == "") ? null : cookie["Type"].ToString();
string Username = (cookie["Username"] == null || cookie["Username"] == "") ? null : cookie["Username"].ToString();
ViewBag.Message = Type;
ViewBag.Username = Username;
try
{
string ReplaceEventID = EventId.Replace('-', '/');
ViewBag.Message = ReplaceEventID;
IEnumerable<Job> JobListRelatedToEvent = DBContext.Jobs.Where(x => x.EventId == ReplaceEventID);
return View(JobListRelatedToEvent);
}
catch
{
return View();
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
UPDATE:
When it run on my local machine it works fine, but after i published to the server I got this error.
Can anyone tell about what's the wrong?
I am facing the same issue and this issue we are getting if the custom error is on.
What you need to do the changes in web.config and add the below code.
So, you will get the actual error of the application or in code level.
<system.web>
<customErrors mode="Off" />
Now insted of generic page of IIS it will shows the error.
I don't know if it will help you, but I ran into an issue where the POST action had [RequireHttps], but the GET didn't. That caused the issue for me. So, check you don't have restrictions on one verb and not the other, especially with a form post.
The issue didn't show until I published to Production because DEBUG directives removed the [RequireHttps] attribute :)
TRY THIS :
public ActionResult Job(string EventId)
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["User"];
if (cookie != null)
{
string Type = (cookie["Type"] == null || cookie["Type"] == "") ? null : cookie["Type"].ToString();
string Username = (cookie["Username"] == null || cookie["Username"] == "") ? null : cookie["Username"].ToString();
ViewBag.Message = Type;
ViewBag.Username = Username;
try
{
string ReplaceEventID = EventId.Replace('-', '/');
ViewBag.Message = ReplaceEventID;
IEnumerable<Job> JobListRelatedToEvent = DBContext.Jobs.Where(x => x.EventId == ReplaceEventID);
return View(JobListRelatedToEvent);
}
catch
{
return View();
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
Related
I am trying to add bindings to a website in IIS with C# code. It seem to work on my local computer, but not on the hosting server (Windows Server 2022). Adding http-binding works, but commit after https causes NullReferenceException, and i am wondering if any of you can explain to me why?
My code is like this (i replaced my actual domainname with . "sitename" and "hostHttpsBinding" always exists with the certificate i want to use):
public static bool AddBindings(IConfiguration configuration, ILogger logger, string subdomain)
{
if (string.IsNullOrWhiteSpace(subdomain)) return false;
try
{
var server = new ServerManager();
var sitename = EnvironmentHelper.IsProd(configuration) ? "<domain>.no" : "test.<domain>.no";
var hostname = $"{subdomain.ToLowerInvariant().Trim()}.<domain>.no";
var site = server.Sites.FirstOrDefault(a => a.Name == sitename);
if (site == null) return false;
logger.LogInformation($"IIS: Sitename {sitename} found. Trying to add bindings...");
var hostHttpsBinding = site.Bindings.FirstOrDefault(a => a.BindingInformation == $"*:443:{sitename}");
var httpBinding = site.Bindings.FirstOrDefault(a => a.BindingInformation == $"*:80:{hostname}");
var httpsBinding = site.Bindings.FirstOrDefault(a => a.BindingInformation == $"*:443:{hostname}");
if (httpBinding != null && httpsBinding != null) return false;
if (httpBinding == null)
{
site.Bindings.Add($"*:80:{hostname}", "http");
logger.LogInformation($"IIS: Http-binding added for {hostname}");
}
if (httpsBinding == null)
{
logger.LogInformation($"SSLName: {hostHttpsBinding.CertificateStoreName}, Hash: {hostHttpsBinding.CertificateHash}");
site.Bindings.Add($"*:443:{hostname}", hostHttpsBinding.CertificateHash, hostHttpsBinding.CertificateStoreName, SslFlags.Sni);
logger.LogInformation($"IIS: Https-binding added for {hostname}");
}
server.CommitChanges();
server.Dispose();
return true;
}
catch (Exception e)
{
logger.LogError($"IIS: Something went wrong when adding bindings: {e.Message}, {e.InnerException.Message}");
return false;
}
}
This is my error message:
ERROR|Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer|Connection ID "16717361851964326032", Request ID "40000091-0008-e800-b63f-84710c7967bb": An unhandled exception was thrown by the application.|System.NullReferenceException: Object reference not set to an instance of an object.
I have the following code that needs to return a single value. However, I keep on getting null (the field Notifications_Id = 0) even though it clearly exists in the database.
var role = _context.AssignedTickets.FirstOrDefault(a => a.Notifications_Id == incidence.Notifications_Id);
I am using Net Core 5
Below is my code
public async Task<ActionResult> EditTicket(int? id)
{
{
if (id == null)
{
return StatusCode(400);
}
Incidence incidence = await _context.Incidences.FindAsync(id);
if (incidence == null)
{
return StatusCode(401);
}
return View(incidence);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditTicket(Incidence incidence)
{
var role = _context.AssignedTickets.FirstOrDefault(a => a.Notifications_Id == incidence.Notifications_Id);
if (role == null)
{
return StatusCode(404);
}
role.Status = "C";
role.ClosedOn = DateTime.Now;
if (ModelState.IsValid)
{
DateTime Timeup = (DateTime)role.ClosedOn;
DateTime Timedown = (DateTime)role.CreatedOn;
long DiffTicks = (Timedown - Timeup).Ticks;
role.TurnAroundTime = Math.Abs(DiffTicks).ToString();
_context.Entry(incidence).State = EntityState.Modified;
_context.SaveChangesAsync();
return RedirectToAction("Dashboard", "Agent");
}
return View(incidence);
}
Please use var role = _context.AssignedTickets.FirstOrDefault(a => a.Notifications_Id == 29); to get the object, and then compare whether the attributes inside match the database.
I read your post and all comments carefully. What everyone said is very reasonable, and the code in the post is not problematic.
So I think the problem is likely to be a problem with the string connecting to the database, that is, a different database is used.
I have login controller and in this i get my session values
[HttpPost]
public ActionResult Login(Models.AdminUsers adminUsers)
{
try
{
if (Session["iUserId"] != null || GetCookie("iUserId") != null)
{
return Redirect("/Home/Index");
}
if (ModelState.IsValid)
{
using (Data.DataClassesDataContext dc = new Data.DataClassesDataContext())
{
var resultUsers =
(from tableAdminUsers in dc.AdminUsers
where
tableAdminUsers.cEmail == adminUsers.cEmail &&
tableAdminUsers.cPassaword == new Class.AesCryption().Encryption(adminUsers.cPassaword) &&
tableAdminUsers.iActive == 1
select new Models.AdminUsers
{
iUserId = tableAdminUsers.iUserId,
cEmail = tableAdminUsers.cEmail,
cUserName = tableAdminUsers.cUserName,
cUserSurname = tableAdminUsers.cUserSurname,
cImage = tableAdminUsers.cImage
}).FirstOrDefault();
if (resultUsers != null)
{
if (adminUsers.lBeniHatirla == false)
{
Session.Add("iUserId", resultUsers.iUserId);
Session.Add("cEmail", resultUsers.cEmail);
Session.Add("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
Session.Add("cUserSurname", resultUsers.cUserSurname.ToUpper());
Session.Add("cImage", resultUsers.cImage);
}
else
{
CreateCookie("iUserId", resultUsers.iUserId.ToString());
CreateCookie("cEmail", resultUsers.cEmail);
CreateCookie("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
CreateCookie("cUserSurname", resultUsers.cUserSurname.ToUpper());
CreateCookie("cImage", resultUsers.cImage);
}
return Redirect("/Home/Index");
}
else
{
ViewBag.iSonuc = -7;
}
}
}
else
{
ViewBag.iSonuc = -6;
}
}
catch (Exception Ex)
{
new Class.Log().Hata("AdminUsers", "AdminUsers_Post", Ex.Message);
}
return View();
}
And i want to control to session in another controller but my session value return null. My control like this :
if (Session["iUserId"] == null && GetCookie("iUserId") == null)
{
return Redirect("/AdminUsers/Login");
}
int iUserLogin = 0;
if (Session["iUserId"] != null && Convert.ToInt32(Session["iUserId"]) > 0)
{
iUserLogin = Convert.ToInt32(Session["iUserId"]);
}
else if (GetCookie("iUserId") != null && Convert.ToInt32(GetCookie("iUserId")) > 0)
{
iUserLogin = Convert.ToInt32(GetCookie("iUserId"));
}
if (Session["iUserId"] == null && GetCookie("iUserId") == null) this row return true and redict to login page again.But i getting cookie correctly Why session value return null?
Where am I making mistakes? Can you help me?
If it is a .net core, use httpcontext. You can solve it using a distribution cache such as Redis. https://learn.microsoft.com/tr-tr/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0
If you want to develop a User Manager
Use a thirty part nuget like Jwt. What it does is sso logic gives you a token for the user you use it
Try using Session with HttpContext as below:-
HttpContext.Current.Session["iUserId"]=value;
Alternativly, you can try using TempData rather then Session.
TempData["iUserId"]=value;
There is a localization function that I use for language change, in this function I am changing the value of the culture using thread, I realized that this function resets my session value.
I am trying to redirect to some page after login.
Here is my code
ViewBag.userid = Session[Declaration.sUserID];
var userid = ViewBag.userid;
if (userid == null)
{
Response.Redirect("signin?url=" + Server.UrlEncode(Request.Url.AbsoluteUri));
}
else
{
string ReturnUrl = Convert.ToString(Request.QueryString["url"]);
if (!string.IsNullOrEmpty(ReturnUrl))
{
Response.Redirect(ReturnUrl);//http://localhost:55197/usermanagement
}
else
{
return RedirectToAction("DashBoard");
}
}
return View();
The problem is that it is not redirecting from Response.Redirect part and always calls the same view again and gain.
Someone have an idea why it's happening?
You need to "return" once you call Response.Redirect, otherwise the code will continue and eventually call return View(), which returns the original view back to the caller. e.g.
ViewBag.userid = Session[Declaration.sUserID];
var userid = ViewBag.userid;
if (userid == null)
{
return Redirect("signin?url=" + Server.UrlEncode(Request.Url.AbsoluteUri));
}
else
{
string ReturnUrl = Convert.ToString(Request.QueryString["url"]);
if (!string.IsNullOrEmpty(ReturnUrl))
{
return Redirect(ReturnUrl);//http://localhost:55197/usermanagement
}
else
{
return RedirectToAction("DashBoard");
}
}
return View();
I have this controller :
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Files"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "Success";
}
catch (Exception ex)
{
ViewBag.Message = "Error:" + ex.Message.ToString();
}
return RedirectToAction("NewController", new { myFile : file });
}
My new controller :
public ActionResult NewController(HttpPostedFile myFile)
{
}
I want to pass "file" to the NewController but it gives me an error at RedirectToAction. How can I pass correct values to RedirectToAction so that it will work? Thanks.
The File is potentially very complex object and you can't pass potentially complex object in simple RedirectToAction. So you have to store File in Session to get it in your next redirection but storing data in Session is not good due to performance perspective and you have to set Session null after retrieving of data from it.
But you can use TempData instead which remains alive during subsequent requests and it immediately destroyed after you retrieved data from it.
So just add your file in TempData and retrieve it in New Controller Action.
Another thing that i noticed that you are storing Message in ViewBag. But ViewBag becomes null during redirection, so you won't be able to get ViewBag.Message in your NewControllerAction action. To make it accessible in your NewControllerAction, you have to store it in TempData but Message is going to have simple string so you can pass it as parameter to NewControllerAction action.
public ActionResult Index(HttpPostedFileBase file)
{
string Message = string.Empty;
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
file.SaveAs(path);
Message = "Success";
}
catch (Exception ex)
{
Message = "Error:" + ex.Message.ToString();
}
//Adding File in TempData.
TempData["FileData"] = file;
return RedirectToAction("NewControllerAction", "NewController", new { strMessage = Message });
}
In your new controller:
public ActionResult NewControllerAction(string strMessage)
{
if(!string.IsNullOrWhiteSpace(strMessage) && strMessage.Equals("Success"))
{
HttpPostedFileBase myFile = TempData["FileData"] as HttpPostedFileBase;
}
else
{
//Something went wrong.
}
}