Convert Exception Into HTTP 404 Response In Application Error

May 11, 2010

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)
err = err.GetBaseException();
var noObject = err as ObjectNotFoundException;
if (noObject != null)
var handled = noObject != null;
if (!handled)
Logger.Fatal("Unhandled exception has occured in application.", err);
private void HandleObjectNotFound() {
// 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:

1-What is the proper way of translating AnException into HTTP 404 response?
2- How does customErrors section work when handling exceptions in Application_Error?
3- Why throwing HttpException(404) renders (blank) page with success (200) status?

View 1 Replies

Similar Messages:

Setting Response / Status Generates "HTTP Status String Is Not Valid" Exception?

Jan 9, 2011

I'm writing an HTTP handler in ASP.NET 4.0 and IIS7 and I need to generate a file-not-found condition.

I copied the following code from Mathew McDonald's new book, Pro ASP.Net 4 in C# 2010. (The response variable is an instance of the current HttpResponse.)

response.Status = "File not found";
response.StatusCode = 404;

However, I found that the first line generates the run-time error HTTP status string is not valid.

If, instead of the lines above, I use the following:

response.Status = "404 Not found";

Then everything seems to work fine. In fact, I even see that response.StatusCode is set to 404 automatically.

My problem is that I don't want this to fail on the production server. So I'd feel much better if I could understand the "correct" way to accomplish this. Why did the first approach work for Mathew McDonald but not for me? And is the second approach always going to be reliable?

View 1 Replies

Throwing Exception Message Giving Internal Server Error HTTP Code 500 On Live Site

Oct 4, 2010

using 2005

when a user enters a bad email I am doing a check on this and throwing an exception message as follows, this works fine on the test site but for some reason the same code on the live site gives a "internal server error" (http code 500). The code below:


not certain why this is happening, I assume that it's some server or config difference between the test and live sites. has anyone seen this before? For a quick fix i'm registering javascript alert and showing the same text so it works but I would like to figure out why the code above is not working.

View 1 Replies

C# - HTTP 502 Proxy Error - The Size Of The Response Header Is Too Large. Contact Your ISA Server Administrator. (12216)

Feb 23, 2011

Some of my users are getting the following error

HTTP 502 Proxy Error - The size of the response header is too large. Contact your ISA server administrator. (12216) Internet Security and Acceleration Server

I am guessing it has to do with the size of hidden "__ViewState" tag in my ASP.NET pages.

I also realize that this is restriction imposed to by IT on the users end and I have no contol over it.

I disabled ViewState on all the controls in my ASP.NET pages. However, __ViewState is still generated very large (as always) to persist control-state (e.g. checkbox, radiobutton, etc.)

View 2 Replies

MVC :: Deploying Application To IIS7 - HTTP Error 404.3

Mar 15, 2010

I have published my site using Visual Stuido's 2008 publish feature. I have then copied these files to a windows 2008 web server with IIS7 installed, it also has .net 3.5 sp1 and MVC installed In IIS I added the site using the 'Add a new site' right click option and then pointed this at the directory my site files are located in, I used the default application pool and it is set to integrated. Then when I attempt to browse I got the error message The Web server is configured to not list the contents of this directory. So I added Default.aspx to the default document list and I then get the following error message

HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map. Has anyone got any ideas on what I do next ? I have read lots of articles on this online but most are confusing and dont explain the solution in simple terms Surely it should be pretty straightforard to just deploy an MVC website to IIS7

View 4 Replies

Show Error In Application When Exception Occur In Webs Service?

Aug 11, 2010

how can we show error in our application when exception occur in webs service

View 10 Replies

Web Forms :: Any Exception Thrown By Application Displayed As Javascript Error

Mar 17, 2011

Recently I have upgraded my app from .net 2.0 to 4.0. By running application under .net 4.0 I get one strange behaviour. Whenever application throw any error, instead of displaying it in browser with call stack, the error is shown in the browser's error window as javascript error and the whole web page remain as it is. is it feature of .net 4.0 or I need to do some settings to display error in web page.

View 3 Replies

C# - Routing On IIS 6 Compiled Web Application / HTTP Error 404 - File Or Directory Not Found

Jun 30, 2010

I have a web application and I'm using routing. When I publish it with the Only files needed to run this application selected it gives me an error when I'm loading any of the page "HTTP Error 404 - File or directory not found."

but if I choose publish All files it works fine.

Do you know how to resolve this issue?

View 1 Replies

Visual Studio :: JIT Degugging - Error - Unhandeled Exception Has Occured In Your Application?

Jun 10, 2010

am working on web application in Viasual studio 2008 using ASP.NET with vb.

when i try to debug the web i got this error

Unhandeled Exception has occured in your application.

View 1 Replies

Forms Data Controls :: 2.0 - System.out Of Memory Exception Error When Access The Web Application

Apr 16, 2010

I am working on a ASP.NET 2.0 application. I get the following exception sometimes when i access the web application. I believe it is related to the server where the application is hosted? Exception of type 'System.OutOfMemoryException' was thrown. 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.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace:

[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0
System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +43
System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +127
System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +142
System.Reflection.Assembly.Load(String assemblyString) +28
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +46
[ConfigurationErrorsException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +613
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +203
System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +105
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +178
System.Web.Compilation.BuildProvidersCompiler..ctor(VirtualPath configPath, Boolean supportLocalization, String outputAssemblyName) +54
System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +227
System.Web.Compilation.BuildManager.CompileGlobalAsax() +52
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +337
[HttpException (0x80004005): Exception of type 'System.OutOfMemoryException' was thrown.]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +58
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +512
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +729
[HttpException (0x80004005): Exception of type 'System.OutOfMemoryException' was thrown.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +8890735
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +85
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +259

What can be the reason for this error and what to check on the code or the server?

View 8 Replies

Convert To Web Application Error - Could Not Parse Aspx File?

Oct 13, 2010

I occasionally get errors in my aspx files which are caused by problems with the designer file. When this happens I delete the designer file, right click on the aspx file and select "Convert to Web Application".

Usually regenerating the designer file works perfectly, however sometimes I get an error which simply says "Could not parse the file pathToFile.aspx". When this happens there are no useful errors displayed in the error panel which would indicate what the problem is. I got this error a little while ago, did some searching and found a blog which explains how to get round this problem. It suggests closing the file, cleaning the project, rebuilding then tring again. VS should now give you a more useful error message which pinpoints the problem. This has worked for me in the past, but doesn't work all the time.Has anyone found a better way of identifying the problem in the aspx file when the "Could not parse file" error is displayed?

View 1 Replies

Web Forms :: Redirecting To A Page At Server / Error Is Http 500 Or Http 403

Dec 2, 2010

I am having problem redirecting error when error is http 500 or http 403 locally running this site there is no problem it gets redirected to my errorpage.aspx. But when deployed at server, it does not get .tried putting try and catch in page_load and in global.asax and I have set Application_Error to redirect to that page and also set <customErrors defaultRedirect to that page also


View 9 Replies

C# - MP3 Download In An HTTP Response?

Jun 9, 2010

I've a question about something I'm searching for,for too long! We've build an application from which an admin upload songs into a database. Then user can bought songs and download it individualy. The problem is that when user download MP3 songs with the code below, it works great in Firefox and Chrome but not in IE8 simply because WMP trying to open the songs and it just don't get it instead of having a "Save as" dialog? Any issue on HOW can i force to have the "Save As" diaglog? Note that I have not MP3 physicaly on server it's in database. So I can't direct link to song ...

Here's my code :

// Remove "specials chars"
foreach (char aChar in @"/:*?""<>| ") {
if (aChar == ' ') {
songNameAndExt = songNameAndExt.Replace(' ', '_');
} else {
songNameAndExt = songNameAndExt.Replace(aChar.ToString(), string.Empty);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.Headers.Add("Content-Disposition", string.Format("filename={0}", songNameAndExt));
HttpContext.Current.Response.OutputStream.Write(songData, 0, songLength);

View 1 Replies

HTTP Response And Request In Binary

Feb 21, 2010

I need to I can make the web request to a webservice which take a XML argument. And is expected to return a Binary response. I am able to make the request but while recieving the response back I am unable to get the response in binary. When I read the response
using streamreader see the header and some attached "HEBRISH" words probably binary but unable to sepreate it out. Please help in seprating out the binary the response data.

View 1 Replies

Web Forms :: Get Response Value - From Http Post

Mar 23, 2011

What wrong with this code?


I would like the numeric values of the enum of Response.StatisCode

View 1 Replies

Custom HTTP Response C# And Ajax?

Apr 4, 2011

I'm trying to query a database that contains information about a "ticket" using jQuery's .ajax() method.

type: 'GET',
url: 'Preview.ashx',
data: 'ticketID=' + ticketID,
success: function (data) {
// 'data' should be a row from the database, so it should be like an
// array that contains each column of the row
// do stuff with this data
... so that all works fine. I'm having trouble with the data variable. On the server side, I do...
// get the ticket ID from the POST parameter
int ticketID = context.Request["ticketID"] != null ? Convert.ToInt32(context.Request["ticketID"]) : -1;
if (ticketID >= 0) {
// grab the data from the database, getInfo() will retrieve the row
// in the DB that corresponds to the ticket ID given, returning an
// ArrayList with all of the information
ArrayList theTicket = getInfo(context, ticketID);
// now, I need to somehow return this information so that I could deal with it
// in the 'success' callback function above
} else {
// something went wrong with the 'newTicket' POST parameter
context.Response.ContentType = "text/plain";
context.Response.Write("Error with 'ticketID' POST parameter.

I've debugged this enough to be sure that the ArrayList contains the correct information. Now I just need to return it. How would I do this? How would I return the data in the ArrayList? Is it possible to structure the response so that I could do data.ID, data.otherColumnName, etc... in the callback function to access the different fields?

View 3 Replies

Suppressing HTTP 500 Response Codes

Feb 10, 2010

I've had a bit of feedback from some threat and vulnerability folks relating to websites returning HTTP 500 response codes. Essentially the advice is that all possible measures must be taken to avoid the server throwing a 500 (i.e. extensive form input validation) which is fine. However, the advice also suggested that attempts to compromise security by means such as inserting a tag into a random query string causing ASP.NET request validation to fire or manipulating viewstate also should not return an HTTP 500. Obviously the native framework behaviour is to interpret the request and possibly throw to a custom error page but even this will return a 500 response code.

So I'm after some thoughts on how to approach this. Is there any way to configure the app at either the .NET level or IIS level to return an HTTP 200 when a 500 is raised? Or does this become a coding exercise at global.asax level in one of the application events? Are there other consequences to consider? BTW, the rationale from the security side is that apps which return HTTP 500 may be viewed as "low hanging fruit" by bots randomly scanning for vulnerabilities and prompt further malicious activity. attempts I'm personally not convinced that changing response codes offers any real security gains but am happy to hapy to take the advice of the pros.

View 3 Replies

Response - Get Custom Http Header?

May 14, 2010

I have an appliction on the one server. There I've added code on server-side in Page_Load:

Response.AddHeader("key", "password-key-from-hotel");

On the client side I have a form:
<form ... action="" >
<input type="hidden" id="asd" value="fgh" >
<script type="text/javascript">

Then on the other domain - there is also my other application - I'm trying to get the hedaer "key" by this code:


But there is no such header. Is there is a desicion? Where is my mistake?

View 2 Replies

Add Response Http Headers In Web Configuration?

May 27, 2010

In my application I need to set a http response header. I'd like to do this in web.config. but I dont'know if this is possible and I can't find it on Google. Solution Finally, after a long search I found the solution. Create a class with this code:

public class myHTTPHeaderModule : IHttpModule
#region IHttpModule Members
public void Dispose()
public void Init(HttpApplication context)
context.EndRequest += new EventHandler(context_EndRequest);
void context_EndRequest(object sender, EventArgs e)
HttpResponse response = HttpContext.Current.Response;
response.AddHeader("Content-Language", "*");

(Don't ask me why to use this event, but it works..) Now add a line in web.config in the HttpModule section:

<add type="namespace.myHTTPHeaderModule, assembly name" name="headers" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

View 4 Replies

HTTP 404 - File Not Found Instead Of MaxRequestLength Exception?

Jan 19, 2011

I have a file upload control on my page. The maximum request length set is 8 MB (maxRequestLength = 8192). I also have server validation that throws an error if the file is more than 4MB. The reason that its 8MB in the config is the leverage that's given to the user and also that the app can be tested.

If I upload a file that's 9MB, I get thrown an exception "Maximum request length exceeded.", which is fine and as expected.

But when I try to upload a file that's 1GB, it shows me a HTTP 404 - File not found. how can I get it throw me a maxRequestLength exception?

I'm using IIS6.

View 2 Replies

C# - Exactly Does Response.Redirect("~/...") Put In The HTTP Response?

Nov 24, 2010

I've just finished reading URL vs. URI vs. URN, in More Concise Terms, and it's really helped understand the distinction between the three terms. Since then I've skimmed the RFC2141 and RFC2616 specs and Microsoft's Response.Redirect Method documentation in an effort to answer the following question confidently.

Given this line of code:


And this resulting HTTP response (trimmed for context):

Status=Found - 302 Date=Wed, 24 Nov
2010 17:27:58 GMT

What name(s) most properly describes what has been placed into the "Location" header?

URL? URI? URN? URC? Which is it?

View 5 Replies

Creating Dynamic Http Response From Component

May 14, 2010

I've developed a component which processes online payments. At a specific point the user must be redirected to the selected acquirer web site for authentication. The acquirer itself suggests that there should be a web page which does it. Something such as the following,

<html xmlns="[URL]">
<head id="Head1" runat="server">
<script type="text/javascript">
function Go() {
<body onload="Go();">
<form id="form1" runat="server" method="post" action="/...">
<asp:HiddenField ID="MID" runat="server" />
<asp:HiddenField ID="Amount" runat="server" />
<asp:HiddenField ID="ResNum" runat="server" />
<asp:HiddenField ID="RedirectURL" runat="server" />

This page redirects the user and posts required arguments to the acquirer's web site. Prior to this page there is another page with a payment button (for example). In the click event of the payment button my component is instantiated and required calculation is done. Something such as the following,

protected void btnPayment_Click(object sender, EventArgs e)
var paymentProcessor = new NS.PaymentProcessor(/*required arguments*/);
NS.Result result = paymentProcessor.Calc();
Session.Add("PaymentProcessResult", result);
catch (Exception p)
throw p;

What I'm going to do is to generate [TakeOff.aspx] page at run-time by the payment processor component instead of having static page (I mean aspx pages that are generated during development phase). The reason why is that we may have different acquirers and each acquirer requires its own arguments to be posted. So if the payment processor component generates aspx or even html pages at run-time we do not need recompile and redeploy the web application.

My problem is that I do not know how to generate aspx pages at run-time. I'm not an ASP.NET guru and all efforts that I've made using HttpResponse were in vain as the original page does not transfer the control to the generated page.

View 1 Replies

HTTP Response Behavior - Cause Browser To Prompt

Jan 5, 2011

I have two very similar pieces of ASP.NET code that send a file in an HTTP Reponse to the client. They should cause the browser to prompt to save the file. The first one works, the second one doesn't. The HTTP responses as seen in Fiddler are below.

HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 228108
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
content-disposition: attachment; filename=Report.xlsx
Date: Wed, 05 Jan 2011 12:17:48 GMT
<binary data>

Not working:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/
Date: Wed, 05 Jan 2011 12:19:21 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 228080
content-disposition: attachment; filename=report 2.xlsx
Cache-Control: private
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Connection: Close
<binary data>

When the first one is seen in Fiddler the browser correctly prompts to save the file. When the second one is seen in Fiddler, nothing observable happens in the browser. Same behaviour in both chrome and firefox.

EDIT: ASP.NET code that produces the second response

Response.Buffer = false;
Response.ContentType = @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-length", genstream.Length.ToString());
Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", filename));
byte[] buffer = new byte[1024];
genstream.Position = 0;
int n;
while ((n = genstream.Read(buffer, 0, 1024) ) > 0)
Response.OutputStream.Write(buffer, 0, n);

View 4 Replies

Sending OK Response Over HTTP To Webpage Request

May 12, 2010

I am using an SMS Gateway to make my application receive SMSs. For this, the SMS Gateway sends a request to one of the pages in my application with the message as a querystring parameter. eg.[URL]. Now after my page gets invoked, I need to send an OK response to the SMS Gateway so that it doesn't keep retrying to send the same message to my application again and again. I cannot figure out how to send the OK response.

View 1 Replies

MVC :: How To Test Action Which Alters Http Response

Apr 27, 2010

How can I unit test an action which alters the Http Response object? I haven't been able to solve this. I can mock the object but can't see how I can check the value after the action runs. I set the Response.StatusCode when errors occur in ajax requests and need to check it has been set in the unit test. The only alternative I can see is to change all my actions to return json objects with a IsSuccessful flag or similar.

View 5 Replies

Copyrights 2005-15, All rights reserved