Server.Transfer does not work? - asp.net

I want to redirect to another page using Server.Transfer and I have this simple code:
if (Page.IsPostBack)
{
try
{
Server.Transfer("AnotherPage.aspx");
}
catch (Exception)
{
throw ;
}
}
But I'm getting an error: "Error executing child request for AnotherPage.aspx.". Could not find the solution on the net.
Just to mention, Response.Redirect works flawlessly.

The error is likely caused by something in AnotherPage.aspx. You may want to insert a try... catch handler in AnotherPage.aspx's Load event.

Related

Application_Error takes precedence over Page_Error

I have both Page_Error method in page that raises error, and Application_Error in global.asax. When Page throws exception, executed routine is Application_Error. But for that one particular page I would like to have different handling in Page_Error. Is there any way to achieve it?
Thanks,
Pawel
P.S. Perhaps it is because exception being thrown is caused by too large file being uploaded (I tested file upload page how it handles files bigger then web.config setting) and Page_Error is not yet wired?
From the same the function of Page_Error you can check for the page and if is the one you look you have diferent behavior.
if( HttpContext.Current.Request.Path.EndsWith("YourFileName.axd", StringComparison.InvariantCultureIgnoreCase))
{
// the diferent way
}
else
{
}
The next way is from inside the page with the diferent behavior.
public override void ProcessRequest(HttpContext context)
{
try
{
base.ProcessRequest(context);
}
catch (Exception x)
{
// here is the different, since you catch here is not move to the Page_Error
// except is a code error... in any case you can do an extra error clear.
}
}

ASP.NET Health Monitoring 404 Event

Does HealthMonitoring have a built-in event that catches 404 errors? I have tried setting up all events (by using webBaseEvent) and I've searched for two days, but I cannot find or trigger an event for a file not found.
I could create my own, but was hoping there was a built in event.
No, it doesn't. You'd have to create a custom event (from webrequesterrorevent) to have HM track it for you.
How to:
Something like this (from memory) in Application_Error in global.asax -
public void Application_Error()
{
var exception = Server.GetLastError() as HttpException;
if (exception != null && exception.GetHttpCode() == 404)
{
//custom error
new Http404Event(this, exception).Raise();
}
}

Response.Redirect() ThreadAbortException Bubbling Too High Intermittently

I understand (now) that Response.Redirect() and Response.End() throw a ThreadAbortException as an expensive way of killing the current processing thread to emulate the behaviour of ASP Classic's Response.End() and Response.Redirect methods.
However.
It seems intermittently in our application that the exception bubbles too high. For example, we have a page that is called from client side javascript to return a small string to display in a page.
protected void Page_Load(object sender, EventArgs e)
{
// Work out some stuff.
Response.Write(stuff);
Response.End();
}
This generally works, but sometimes, we get the exception bubbling up to the UI layer and get part of the exception text displayed in the page.
Similarly, else where we have:
// check the login is still valid:
if(!loggedin) {
Response.Redirect("login.aspx");
}
In some cases, the user is redirected to login.aspx, in others, the user gets an ASP.NET error page and stack dump (because of how our dev servers are configured).
i.e. in some cases, response.redirect throws an exception all the way up INSTEAD of doing a redirect. Why? How do we stop this?
Have you tried overloading the default Redirect method and not ending the response?
if(!loggedin) {
Response.Redirect("login.aspx", false);
}
You can use the following best-practice code instead, as explained by this answer to prevent the exception from happening in the first place:
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
Since I was looking for an answer to this question too, I am posting what seams to me a complete solution, rounding up the two above answers:
public static void Redirect(this TemplateControl control, bool ignoreIfInvisible = true)
{
Page page = control.Page;
if (!ignoreIfInvisible || page.Visible)
{
// Sets the page for redirect, but does not abort.
page.Response.Redirect(url, false);
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline
// chain of execution and directly execute the EndRequest event.
HttpContext.Current.ApplicationInstance.CompleteRequest();
// By setting this to false, we flag that a redirect is set,
// and to not render the page contents.
page.Visible = false;
}
}
Source:
http://www.codeproject.com/Tips/561490/ASP-NET-Response-Redirect-without-ThreadAbortExcep

Error when I am redirecting page

I am getting an error:
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
when I am redirecting my page from one to another.
I am using this code:
try
{
Session["objtwitter"] = obj_UserDetSumit;
Response.Redirect("TwitterLogin.aspx");
}
catch (Exception ex)
{
lblStatus.Text = "Account Creation Failed, Please Try Again";
}
And I got a solution and I tried also this Response.Redirect("home.aspx",false);
It's not throwing an error but it's also not redirecting page.
Try - catch creates a thread around code within it in order to catch exceptions. When you Redirect you are effectively terminating execution of the thread thus causing an error since execution ended unnaturely (though this is by design). You should not Redirect from within try-catch and if you do you should use Response.Redirect( "some url", false ); and also specifically catch ThreadAbortException.
Reference here: http://msdn.microsoft.com/en-us/library/t9dwyts4.aspx
Response.Redirect calls the Response.End, which throws a ThreadAbortException, so you'd want to change your code to:
try
{
Response.Redirect("home.aspx");
}
catch(System.Threading.ThreadAbortException)
{
// do nothing
}
catch(Exception ex)
{
// do whatever
}
First, make sure that you are working with a debug build and not a release build of your project. And second, make sure that you are debugging in mixed mode (both managed and native) so that you can see all of the current call stack.
I'd try moving your Response.Redirect outside of the try catch block like this:
try
{
Session["objtwitter"] = obj_UserDetSumit;
}
catch (Exception ex)
{
lblStatus.Text = "Account Creation Failed, Please Try Again";
return;
}
Response.Redirect("TwitterLogin.aspx");
Most people having this issue here resolved it with calling Response.Redirect("TwitterLogin.aspx", false); which doesn't explicitly kill the thread immediately. I'm not sure why this didn't work for you.
I think the issue is having your Response.Redirect inside of a try catch block. Calling Response.Redirect(url); calls Response.End();, which will throw a ThreadAbortException.
Make sure you're not trying to do any more processing after you do your redirect.
Using Reflector, you can see that Response.Redirect(url); calls Response.Redirect(url, true);
Passing true then calls Response.End(); which looks like this:
public void End()
{
if (this._context.IsInCancellablePeriod)
{
InternalSecurityPermissions.ControlThread.Assert();
Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}
....
}
Even though you don't have a finally in your code snippet, it may be trying to execute the "empty" finally, but can't because the thread is being aborted. Just a thought.
If you replace your code these line you won't get an exception in the first place
try
{
Response.Redirect("home.aspx", False);
//Directs the thread to finish, bypassing additional processing
Context.ApplicationInstance.CompleteRequest();
}
catch(Exception ex)
{
// exception logging
}
Hope it helps

exception (ab)use in web development

I find myself using exception in web development even for conditions that are not really errors, let alone exceptional ones - just logic decisions, validations...
in a web page, I often write code like so:
try
{
int id;
if(!int.TryParse(txtID.Text, out id))
throw new Exception("ID must be an integer");
if(IdAlreadyExists(id))
throw new Exception("ID already exists in database");
//and so on...
}
catch(Exception ex)
{
SetErrorLine(ex.Message);
}
I was wondering if this is really the correct way of using exceptions and enforcing Business Logic in web development.
P.S.: I am using asp.net, and obviously I could use ASP.NET validators for some of these and also seperate UI from logic, but I'm trying to make a point on the general idea.
You've just answered your own question, really.
Exceptions are for exceptional circumstances. Assuming the code you posted is from a page that takes "ID" as input from the user, then it's not exceptional for user input to be bad. Use the validation infrastructure for that, or do it manually, but don't use exceptions for that.
Also, don't get into the habit of displaying Exception.Message to users. It is meant for developers to see to know what went wrong and how to fix it.
I wouldn't consider the first example to be an acceptable use of an Exception. A user could easily screw up entering that information, and user input should be validated anyways.
An exception should be 'exceptional'. Something that you don't expect to happen, shouldn't happen or really don't want to happen. Anything that can be validated or handled before needing to throw an exception should just be treated like an error.
Different communities differ in their acceptable use of exceptions. The Python community is a little bit more liberal with their use of exceptions: http://wiki.sheep.art.pl/Ask%20for%20Forgiveness
I'm a fan of using them as long as it doesn't disrupt the logic of your application.
Just wanted to add that for asp.net adding a global exception handler HttpModule to catch unhandled exceptions is a very clean way to train yourself out of try/catch/finally abuse.
Throw exceptions when the assumptions your methods take on are broken, or if a method simply cannot complete.
In your example, your IdAlreadyExists method might query a database. That method will assume that there is a database to connect to, you have enough memory to do what you need, and so on. If an assumption is broken, throw an exception.
I, for one, like to let lower level code throw exceptions, and higher level code catch exceptions. That's not a hard and fast rule, just a general guideline I like to follow. It's typically not necessary to throw exceptions to the same level, but I could imagine that it would make sense at times.
still missing the way it SHOULD be done
Set an error mesage and return.
Log error and dont display it to user.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int id = 0;
if(!int.TryParse(txtID.Text, out id))
{
SetErrorLine("Thats not a valid number dude! Need to go to school again");
return;
}
if(IdAlreadyExists(id))
{
SetErrorLine("I already have this entry in store. Sorry. Call again!");
return;
}
...the rest of your code
}
catch(Exception ex)
{
_log.Error(ex);
SetErrorLine("Something unexpected happened dear user ... ");
}
}
Edit: your comment
try {
string error = "";
int id = 10;
if(BO.DoSomething(out error, id, otherParams))
{
SetErrorLine(error);
return;
}
}
catch(Exception ex)
{
//log
}
My guess:
try {
string meaningfullErrorMessage= "";
int id = 10;
if(!BO.DoSomething(out meaningfullErrorMessage, id, otherParams))
{
SetErrorLine(meaningfullErrorMessage);
return;
}
}
catch(Exception ex)
{
//log
}

Resources