A word to be said. This is the best .NET community ever. Keep it up !
I had a problem lately that I managed to have for it 2 solutions and I am wondering which one should I choose.
Here the issue :
When a user requests my site ( www..com), I am gonna redirect him to (www..com/en) because it is a multilingual site.
I am using .NET routing to to that.
In the Page_Load of the default.aspx page I check if the language in the Routing Collection is available, I don't redirect. If it is not available I redirect to (www.___.com/en). Here is the code :
if (Page.RouteData.Values.Count == 0)
{
if (SessionManager.IsUserAuthenticated)
{
开发者_如何学运维 //Redirect To User HomePage for his Main Language
Page.Response.Redirect(UserManager.GetUserMainPageWhenLoggedIn(SessionManager.LoggedUser.LanguageID,true));
}
else
{
Page.Response.Redirect(String.Format("~/{0}", Cultures.en.ToString()), true);
Helpers.SetCulture(Cultures.en.ToString());
}
}
I am using Response.Redirect to do that. Now if I set to End The Response the method parameter, it will throw an exception so I can handle it throught
try
{
this.InitializeLayout();
}
catch (ThreadAbortException ex)
{
}
catch (Exception ex)
{
ExceptionManager.LogException(ex);
}
If I don't end the Response, the page will execute the whole lifecyle, redirect and then do it again which results a double execution of the page.
My main objective is not to execute the page 2 times to minimize processing ( if the site gets hammered by a big traffic). If I end the Response, a ThreadAbortExeption will be thrown and I think this is not good for the site.( I can catch it and not log it).
What do u think guys?
You could avoid throwing the exception by, as you said, passing false to the endResponse parameter. If you want to then avoid executing the page, you could also call HttpContext.Current.ApplicationInstance.CompleteRequest(); which should skip the rest of the code on your page.
Note, however, that postback and render methods will still execute. If you want to avoid that, you must explicitly include code to ignore them. A great example of how to do this by overriding the RaisePostBackEvent and Render methods is here: --> http://www.c6software.com/articles/ThreadAbortException.aspx
You can use the Application_BeginRequest event handler in global.asax file or a HttpHandler to do your redirections. In both cases you will avoid 2 calls being made.
I would also suggest that you use server.Transfer instead of response.redirect.
精彩评论