session throw an error on timeout asp.net - asp.net

I make a code with the session in the payload I test if the error exist :
protected void Page_Load(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(Session["id"].ToString())) QueryStringError.SessionNotFound(Response);
else
{
I redirect to some page if the session is not exist ... but I got these error after some period of time :
Server Error in '/Redcrescent' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 11: protected void Page_Load(object sender, EventArgs e)
Line 12: {
Line 13: if (String.IsNullOrEmpty(Session["id"].ToString())) QueryStringError.SessionNotFound(Response);
Line 14: else
Line 15: {
Source File: c:\Users\Samy\Documents\Visual Studio 2010\WebSites\Redcrescent\User\UserPrivilegeManage.aspx.cs Line: 13
the session timeout is finish but why it gave me the error it should redirect not throw an error
in web.config file :
<sessionState cookieless="true"
regenerateExpiredSessionId="true"
timeout="525600" mode="InProc" stateNetworkTimeout="525600"
/>
but still didn't work ... any idea ?
how to make session never expired ? and how to solve these error ?

You should check for session key first like:
if(Session["id"]!= null)
And then call its ToString method. The reason you are getting the exception (NRE) is because the key doesn't exits in session and you are trying to call ToString on it.

You cannot execute ToString on null but exactly this you're doing if the session value is null here:
if (String.IsNullOrEmpty(Session["id"].ToString())) QueryStringError.SessionNotFound(Response);
You need to check for null separately:
object id = Session["id"];
if(id == null || String.IsNullOrEmpty(id.ToString())
{
QueryStringError.SessionNotFound(Response);
}

replace
if (String.IsNullOrEmpty(Session["id"].ToString()))
with
if (String.IsNullOrEmpty(Session["id"]))

Related

Server.ClearError() with page refresh

I am using ASP.NET custom error page in my application. Following is the web.config file entry for CustomErrors tag
<customErrors mode="On" defaultRedirect="Error.aspx" redirectMode="ResponseRewrite" />
Following is the code snippet on Error.aspx page
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Exception ex = Server.GetLastError();
if(ex != null)
{
CommonUtils.SendException(ex.Message.ToString(), ex.StackTrace.ToString());
Server.ClearError();
}
}
}
If "ex" is not null, code will send the exception email. This works fine.
After sending email, I want to clear all the errors so that no email will be sent in case users hits the refresh button. But even after using Server.ClearError, there is a value return by Server.GetLastError() When page is posted back.
Your code should be rewritten to something like this:
Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
Exception ex= Server.GetLastError();
CommonUtils.SendException(ex.Message.ToString(), ex.StackTrace.ToString());
}
And the Page_Load event of error page should be empty then. As you can read in this MS article: https://support.microsoft.com/en-us/kb/306355 Server.ClearErrors stops error propagation, so If you call it on the page error will not be handled by Application_Error event. If you don't call it in Application_Error then application will look for customErrors declaration in web.config redirect to that page.
If you do not call Server.ClearError or trap the error in the
Page_Error or Application_Error event handler, the error is handled
based on the settings in the section of the Web.config
file. In the section, you can specify a redirect page
as a default error page (defaultRedirect) or specify to a particular
page based on the HTTP error code that is raised. You can use this
method to customize the error message that the user receives.
If an error occurs that is not trapped at any of the previous levels
in your application, this custom page is displayed. This section
demonstrates how to modify the Global.asax file so that
Server.ClearError is never called. As a result, the error is handled
in the Web.config file as the last point to trap the error.

Uploaded 'multipart/form-data' to ASP.NET Web API action, not readable in bufferless mode

I'm building an ASP.NET Web API endpoint that accepts 'multipart/form-data' requests. I implemented it as described in this article using .NET Framework 4.5 and Web API 2.1. A simplified version of the action method I created, looks like this:
public async Task<HttpResponseMessage> PostFile()
{
if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var rootPath = System.Configuration.ConfigurationManager.AppSettings["StorageLocation"].ToString();
var provider = new MultipartFormDataStreamProvider(rootPath);
var response = Request.CreateResponse(HttpStatusCode.OK);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
// Imagine awesome logic here, unicorns and rainbows! Instead of that, we do the following:
response.Content = new StringContent("You uploaded " + provider.FileData.Count.ToString() + " files.");
}
catch (Exception e) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); }
return response;
}
Because the uploaded files can be very big (up to 2GiB), I want my requests to not be buffered by ASP.NET, thus avoiding high memory usage. To realize this I told Web API to stream incoming requests, instead of buffering them, as described in this article. The custom WebHostBufferPolicySelector looks something like this:
public class CustomWebHostBufferPolicySelector : WebHostBufferPolicySelector
{
public override bool UseBufferedInputStream(object hostContext)
{
System.Web.HttpContextBase contextBase = hostContext as System.Web.HttpContextBase;
if (contextBase != null && contextBase.Request.ContentType != null && contextBase.Request.ContentType.Contains("multipart")) return false;
else return base.UseBufferedInputStream(hostContext);
}
public override bool UseBufferedOutputStream(System.Net.Http.HttpResponseMessage response)
{
return base.UseBufferedOutputStream(response);
}
}
I load this guy in the Global.asax, at application start, like this:
protected void Application_Start(object sender, EventArgs e)
{
// Here, other stuff got did.
GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new CustomWebHostBufferPolicySelector());
}
Alright, the board is set, lets get the pieces moving. If I don't use my CustomWebHostBufferPolicySelector, everything works just fine. However, when its used, I get the following exception:
Message: "An error has occurred."
ExceptionMessage: "Error reading MIME multipart body part."
ExceptionType: "System.IO.IOException"
StackTrace: " at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()\ \ --- End of stack trace from previous location where exception was thrown ---\ \ at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\ \ at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\ \ at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\ \ at ..."
With the following inner exception:
Message: "An error has occurred."
ExceptionMessage: "Unable to read the entity body in Bufferless mode. The request stream has already been buffered."
ExceptionType: "System.InvalidOperationException"
StackTrace: " at System.Web.Http.WebHost.HttpControllerHandler.<>c__DisplayClass13.<GetStreamContent>b__10()\ \ at System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent.get_StreamContent()\ \ at System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent.CreateContentReadStreamAsync()\ \ at System.Net.Http.HttpContent.ReadAsStreamAsync()\ \ at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()"
It looks like the request is still buffered somehow, by something else. Is there another place in the ASP.NET pipeline I should be looking? Or even IIS maybe? What are the other places in this request's lifecycle where it can be buffered, and how do I control them?
In an attempt to make the problem more clear and shareable with others, I created a simple project to try and reproduce the problem. While doing this I found the answer: disable all kinds of tracing.
In my case I had ASP.NET's own tracing functionality enabled, and also Glimpse. Both of these buffer the request before it arrives at the Web API action.
For completeness' sake, here the proper way to turn them off in your Web.Config, while testing and in production.
<configuration>
<system.web>
<trace enabled="false" />
</system.web>
<glimpse defaultRuntimePolicy="Off">
</glimpse>
</configuration>
In my case, these two were the culprits, but I can imagine there may be others, so be wary of this.

Membership API ASP.NET

It is necessary to register as soon as this user directly login
protected void Button1_Click(object sender, EventArgs e)
{
Membership.CreateUser(FNBox.Text, PassBox.Text, EmailBox.Text);
FormsAuthentication.RedirectToLoginPage(FNBox.Text);
}
Error:
"Could not find the resource.
Description: HTTP 404. Perhaps the desired resource (or one of its dependencies of components) is removed, has a different name or is temporarily unavailable. Look at the following URL-address and make sure it is correct.
The requested URL: / OrderTest2/login.aspx "
protected void LoginButton_Click(object sender, EventArgs e)
{
Control lgnview = (Control)LoginView2.FindControl("LoginForm");
TextBox usrbox = (TextBox)lgnview.FindControl("UserName");
TextBox pasbox = (TextBox)lgnview.FindControl("Password");
string user = usrbox.Text;
string pass = pasbox.Text;
if(Membership.ValidateUser(user,pass))
{
FormsAuthentication.RedirectToLoginPage(user);
}
}
This is work normally
Your default redirect login page is wrong. As you can see, you are getting a 404 error which means that IIS cannot find your OrderTest2/login.aspx page. Verify your path.
You can set the defaultUrl path in your web.config as below to a valid page path, this will fix the problem.
<authentication mode="Forms">
<forms loginUrl="/OrderTest2/login.aspx" defaultUrl="myCustomLogin.aspx" cookieless="UseCookies" />
</authentication>

Display Exceptions in ASP.NET / Azure

I have a custom error page in an Azure ASP.NET web app where I'd like to display
<p>Oops - something went wrong.</p>
<p>The most common problem is that you tried to do something that the database enforces shouldn't happen.</p>
<p>The error is:</p>
In web.config I have:
<customErrors mode="On" defaultRedirect="Error.aspx" />
and global.asax:
protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\nError Message:" + objErr.Message.ToString() +
"\nStack Trace:" + objErr.StackTrace.ToString();
EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error);
}
Problem: How to display the full exception on the Error.aspx page?
Try adding redirectMode="ResponseRewrite" attribute to the customErrors element if you are using ASP.NET 3.5 SP1. That should preserve the exception information stored in Server.GetLastError(). Then you can add a label to the Error.aspx page and display the exception details, i.e. lblError.Text = Server.GetLastError().ToString().
Here's a similar SO question: ASP.NET custom error page - Server.GetLastError() is null

Convert an exception into HTTP 404 response in the Application_Error

First of all, quickly what exactly I want to achieve: translate particular exception into the HTTP 404 so the ASP.NET can handle it further.
I am handling exceptions in the ASP.NET (MVC2) this way:
protected void Application_Error(object sender, EventArgs e) {
var err = Server.GetLastError();
if (err == null)
return;
err = err.GetBaseException();
var noObject = err as ObjectNotFoundException;
if (noObject != null)
HandleObjectNotFound();
var handled = noObject != null;
if (!handled)
Logger.Fatal("Unhandled exception has occured in application.", err);
}
private void HandleObjectNotFound() {
Server.ClearError();
Response.Clear();
// new HttpExcepton(404, "Not Found"); // Throw or not to throw?
Response.StatusCode = 404;
Response.StatusDescription = "Not Found";
Response.StatusDescription = "Not Found";
Response.Write("The whole HTML body explaining whata 404 is??");
}
The problem is that I cannot configure default customErrors to work with it. When it is on then it never redirects to the page specified in customErrors: <error statusCode="404" redirect="404.html"/>.
I also tried to raise new HttpExcepton(404, "Not Found") from the handler but then the response code is 200 which I don't understand why.
So the questions are:
What is the proper way of translating AnException into HTTP 404 response?
How does customErrors section work when handling exceptions in Application_Error?
Why throwing HttpException(404) renders (blank) page with success (200) status?
Thanks,
Dmitriy.
In a few words, you if you manually set HTTP status in Application_Error, you lose possibility to use customErrors section handler, since you call Server.ClearError().
Handle the exception before Application_Error or derive the exception from HttpException.
What is the proper way of translating AnException into HTTP 404 response?
It's better to handle exceptions in Controller. You can introduce base class controller and handle most of exceptions in custom HandleError attribute. You can throw HttpException their and it will be properly handled by customErrors section handler.
You can also derive your ObjectNotFoundException exception from HttpException(404)
Application_Error is the last chance to handle an exception. You have only Response API to handle it. You can manually set status code and write to response or manually trigger redirect to custom error page or call Server.TransferRequest() to existing html or aspx file (not to the controller action). In current asp.net version, you cannot set or change Server.GetLastError in Application_Error method only retrieve or clear it.
How does customErrors section work when handling exceptions in Application_Error?
By calling Server.ClearError() you also clean current request error therefore it is not handled by customErrors section handler
Why throwing HttpException(404) renders (blank) page with success (200) status?
You should no throw any exception in Application_Error method. Exception means that your error handling failed.

Resources