I wrote this code in the global.asax following the classical code. Each time I start the website it shows this error. After i refresh the page, it goes the correct page.I don't understand why.
Response is not available in this context. 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.Web.HttpException: Response is not available in this context.
Source Error:
Line 26: catch (Exception ex) Line 27: { Line 28: Response.Write(ex.ToString()); Line 29: 开发者_开发百科 } Line 30:
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
try
{
if (Roles.RoleExists("Administrators") == false)
Roles.CreateRole("Administrators");
if (Membership.FindUsersByName("ken").Count == 0)
{
Membership.CreateUser("ken", "123", "ken@jobpost.com");
Roles.AddUserToRole("ken", "Administrators");
}
if (Membership.FindUsersByName("dan").Count == 0)
Membership.CreateUser("dan", "123", "dan@jobpost.com");
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
</script>
Application_Start is executed only once when the application is started by IIS. The actual cause of the problem lies in the code inside of the try block, which you can diagnose using a logging framework or by setting a breakpoint inside the catch block.
You may not use Response.Write inside the catch block, as there is no Request (or Response) associated with Application_Start. Doing so triggers a new exception, which hides the original cause of the problem. Look at the ASP.NET Application Lifecycle for more details.
I believe that most probably you have some issue in your app start up code that results into an exception that take you to catch block. For some reason, the response object in not available and therefore you get an un-handled exception. Because application has already started, the code path is not getting visited again and you don't see the error on subsequent request.
I would suggest that you log the exception in a file instead of emitting it in response to check the original exception details that will shade light on actual issue and why response in not available. You can user System.Diagnostic.Trace and trace listeners for logging (or you may use library such as Log4Net or MS Logging App Block)
精彩评论