Difference between error return in ASP.NET MVC - asp.net

Whats difference between return new HttpStatusCodeResult(500) and cause a real error in the action (like division by zero)?
I'm asking because my customErrors works fine when a error like division by zero ocurred, but if i return new HttpStatusCodeResult(500) the customError dont show my page

HttpStatusCodeResult is for notifying the browser of the result of an action, using an actual HTTP status code. For example, if the browser tries to load an image that is no longer available, you could send a 404. If the user is attempting to access a resource that requires authentication, you could return a 401.
Errors caused by your code often don't need to inform the browser of an error, but instead need to inform the user, using an error page with a message. This error page though, would (most likely) be sent to the browser with an HTTP status code of 200.
tldr; these are two different types of errors with different meanings, meant for different recipients.

Related

What status code to return when an invalidly generated link has been clicked?

Consider the following situation:
I have a MVC setup where the view invokes a mapper to get a specific URL for a href attribute. The mapper holds keys to make the referencing easy.
Now the view requests an invalid key, so the mapper responds with say /invalid_url. But the dispatcher knows this URL and when a user clicks the link an error message will be displayed about how bad we feel.
But what if the Google Bot visits this invalid URL?
What would a search engine friendly status code be? I feel like 500 would be appropriate because it is a server side failure. But then this has the feeling of being a temporary error or somehow not related to the URL but to the internal mechanics. The other option that comes to mind is 404. This is also valid because the requested page does not exist. However 4xx errors are client side errors ("You requested the wrong URL. So it's basically your error"). And it just doesn't feel like a client side error to me.
Am I overthinking things? Should I just go with 404?
When I have a question like this, I refer to a site like http://www.restapitutorial.com/httpstatuscodes.html
5xx error codes imply that the server made a mistake. But you're saying the view (client-side) requested the wrong key. That sounds like a client-side error to me. While it's not the user's fault, the server doesn't know this, and the requested URL really doesn't exist. So a 404 would be appropriate.
But this is a weird case, and you should still want to fix the underlying issue of the client consistently(?) requesting a bad url.

Unexpected GET method calls to ASP.NET ScriptService

Our error logger is picking up the following error periodically:
System.InvalidOperationException: Request format is unrecognized for
URL unexpectedly ending in '/TheMethodName'
The reason this error is being thrown is because the request to the script service is using the GET method, and the default security settings only allow POST requests.
The strange part is that the only place in our code where we are calling this particular service method is through an $.ajax call, and it is specifically using type: 'POST'. There is no other place in the app where a GET request is made for this service.
The ui is making the POST call every 20 seconds to retrieve some data, and it does not seem that the GET's are interfering with that -- they are just extraneous. I've looked at the IIS logs, and I can see the proper POST requests, and then sometimes a GET request.
As an added wrinkle, it's not just this web service that is getting the extra GET calls -- we are logging these to several other service endpoints as well.
My guess is that the browser or a proxy server or something is making these calls on its own (like as part of prefetching or some sort of caching), but I have no evidence of that. In looking at the user agent for the bad requests, they are coming in from a variety of browsers.
Has anybody else seen this before, or have an idea of what might be causing it?

Is there anything wrong with sending other content along with a 404 error?

For example, day, in a somewhat REST-oriented environment, a request comes in for an object that doesn't exist, like:
GET http://example.com/thing/5
Is there anything wrong with sending back a 404 response who's body is the same as a a different page? For example, responding like:
404 body: [content from "http://example.com/thing/" which is a list of things]
Does it make any sense to do this? Will this cause any problems with certain browsers? Is it confusing to the user? Or is this perfectly fine to do?
Along these same lines, I would have the content of the 404 response match the request's accept headers as best I could. (ie. abide by content negotiation with the user agent)
For example, a xml or json request would get something along the lines of a simple error message and something that says "look here for similar things", while an html request would get an HTML page that has the error message as well as the content of the list page (as I indicated above)
I think it depends on how the Restful web services are being consumed. If I'm programmatically consuming the web service from a different application, then I would want the status code together and a plain text message instead of a message decorated with HTML tags. I mean, say for example, it doesn't make sense to return a bloated 404 content if your user makes the web service call using Curl because the message will not be readable to them.
You could have different "consumes" for each restful webservice. If it's an XML request, then you return 404 and a plain text message. Otherwise, you return the error page content.
I don't see anything wrong with it. In our webservice we always send back a json error object which includes stacktraces and other details about the response. Even on a regular web server, you get at least text which can be displayed in a browser saying that you got a 404 response.

Suppressing HTTP 500 response codes

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.
To answer your question: global.asax is the correct place, in particular, the Application_Error event handler. You should be able to do something like
Response.StatusCode = 200
Response.StatusDescription = "OK"
there.
PS: Don't do it. :-) To me, this sounds like yet another security-by-obscurity-by-violating-standards approach. I really don't think the (possibly marginal) security increase is worth breaking correct HTTP behavior (think about Google indexing your error pages, etc.).
Why? Sending back a 500 code without any other information does not give an attacker much information.
Provided you don't throw stack trace, state dumps etc, back to the client then you're fine. And I doubt very much you want to do that.
Seriously, just create a "500" page (picture of a whale optional) and return that with your status 500 - it gives nothing away.
Sending a 200 status when the page was NOT generated successfully is plain wrong and may cause bad things to happen - such as bots thinking it is a genuine page. You don't want your "500 error" page showing up on Google because you sent back a 200 status instead.
You can set custom error pages in config - and you could re-set the response status in your custom error page
<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.htm" >
<error statusCode="500" redirect="~/CustomError.aspx"/>
</customErrors>
Serious warning...!
Make sure there aren't any errors EVER in your custom error page. Usually, you would use a html page, not an aspx page - but if you want to change the response headers you may need to use the aspx page. Don't do anything else on there except change the headers (i.e. don't display any data from a database or try to run any logic) and error on your custom error page will cause a "maximum number of redirects" error.

How to stop a 500 .net error created calling the 500 error page

Here's an interesting one for you.
I've got my custom 500.aspx setup which is called when a 500 error occurs in my application. The 500.aspx also sends me an email with the error details.
I've noticed one small problem.
If you attempt an xss attack on the 500.aspx itself, the 500 page is not called.
This is obviously some sort of logic issue.
In fact, microsoft themselves suffer from the same issue.
See it in action here
http://www.microsoft.com/500.aspx?aspxerrorpath=%3Cscript%3Ealert(%22XSS%22)%3C/script%3E
How can I prevent this?
Ed
If you attempt an xss attack on any page, the custom error page will not be called (here's another random page on Microsoft.com with xss in the querystring).
The behavior appears to be intentional to stop the attack dead in its tracks. Even the error message indicates this behavior:
Request Validation has detected a
potentially dangerous client input
value, and processing of the request
has been aborted.
The only workaround appears to be to disable validation or to capture and handle the error in your global on Application_Error.
It appears that once you define a page to handle specific(or non specific?) errors, it is no longer available directly via its url, sorta like the Web.Config cant be called via the browser.
I would set up a 500Test.aspx which throws an exception causing a 500 error (and thus fires the 500.aspx)
That might work.
You might want to think about handling your errors in the Application_Error event in Global.asax.cs instead of the 500.aspx page. You could put the email code there, then redirect the user to an error page after you've done your error handling (this is how we do it where I work).

Resources