filter asp.net healthmonitoring - asp.net

We have activated health monitoring on our website. Recently we are getting a lot of hack attempts which are caused by bots, but also spawn a lot of server errors.
Exception type: System.Web.HttpException
Exception message: The length of the URL for this request exceeds the configured maxUrlLength value.
Request information:
Request URL: http://www.ourdomain.be/Product/Band/29360" onmousedown="return rwt(this,'','','','7','[CUT_OUT_SOME_STUFF]row ab_button" id="am-b6" href="
User host address: ---.---.47.93
How can I filter these particular events so I don't get 10 emails per second?
Or how can I sanitize the URL before it is handled by the security parts of ASP.NET?

I can't totally repro your error - I get an exception for Illegal characters in path instead. Nevertheless...
Quick and dirty = send your emails to a dummy address and set up a
filter/rule on it so only the ones you want get forwarded to you
Slightly less quick = Use Application_Error with
Server.GetLastError() and Server.ClearError() to inspect and ignore
these
Create your own health monitoring provider, though I think you still
need to use Server.GetLastError to retrieve the exception data. See
http://msdn.microsoft.com/en-us/library/ms227676%28v=vs.85%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Related

How do I trap a SerializationException in Web API?

I have an ASP.NET Web API web service which throws a SerializationException in certain circumstances. The problem is that I'm unable to trap and log this exception server-side -- the only place it shows up is in the body of the HTTP response to the client.
I registered an ExceptionFilterAttribute as described in Exception Handling in ASP.NET Web API and verified that it works properly when I throw an exception within my controller. Unfortunately the SerializationException is being thrown during the response (after the controller) and appears to be completely swallowed up by ASP.NET. I also tried hooking Application_Error() in Global.asax.cs but it didn't show up there either.
How can I catch SerializationException exceptions during the Web API response?
If, instead of returning an object, you use the ApiController.CreateResponse() method and return a HttpResponseMessage you can then do response.Content.LoadIntoBufferAsync().Wait() and that will force the serialization to happen whilst you are still in the action and therefore can catch the exception.
BTW, Serialization of responses actually happens at the host layers(in HttpControllerHandler, when hosted in IIS and in HttpSelfhostServer, when hosted in SelfHost) which is way below the stack and not immediately after the response is returned from an action.
WebAPI Stack Poster: http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster-grayscale.pdf
That said, I am not able to come up with a straight forward way to achieve this. This is cumbersome, but may be override the default Xml and Json formatter's WriteToStreamAsync methods and try-catch-log any exceptions?
Alternatively, you can enable Web API Tracing which would log the exceptions happening during serialization. But yeah, if you do not know for the requests which cause the serialization errors, then you might want to enable tracing all the time which i am not sure is something you might want to do.
You can catch all Web API exceptions by registering an implementation of IExceptionHandler.
See Web API Global Error Handling
...there are a number of cases that exception filters can’t handle. For example:
Exceptions thrown from controller constructors.
Exceptions thrown from message handlers.
Exceptions thrown during routing.
Exceptions thrown during response content serialization .
One thing not mentioned in that article is that your IExceptionHandler must be registered, either by GlobalConfiguration.Configuration.Services.Add(...) or via an IoC container configured to be used by DependencyResolver.

What is error code is 0x80070001? And how can I solve it?

I'm getting this error on my web service:
An error occurred while communicating with the remote host. The error code is 0x80070001
The weird thing is that the CPU and memory usage on the server is not high.
The detailed error message:
Error Message:
An error occurred while communicating with the remote host. The error code is 0x80070001.
Stack Trace:
at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect)<br />
at System.Web.Hosting.IIS7WorkerRequest.ReadEntityCoreSync(Byte[] buffer, Int32 offset, Int32 size)<br />
at System.Web.Hosting.IIS7WorkerRequest.ReadEntityBody(Byte[] buffer, Int32 size) <br />
at System.Web.HttpRequest.GetEntireRawContent()<br />
at System.Web.HttpRequest.get_InputStream()<br />
at Service.Upload() in c:\inetpub\path\Service.aspx.cs:line 213
After Google Search:
Thread on Microsoft Forums and I disable the offloading of network card and nothing change :(
Question on Stack OverFlow No answers :(
How can I fix this problem?
More information
Inner Exception Message: The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))
Very Important
This is only happened with a web application, but if I used a web site, nothing happened (no error).
And after a lot of research I think this error is caused by the web.config file.
I receive this error on my site also. I've determined the agent that generally causes this problem and it is a webcrawler like the one used by Google to index pages.
Anyway, I believe the answer is either Cause 1 or Cause 2:
Cause 1
This problem occurs because the client makes an HTTP request by using an HTTP method that does not comply with the HTTP specifications.
Cause 2
This problem occurs because a client makes an HTTP request by sending the POST method to a page that is configured to be handled by the StaticFile handler. For example, a client sends the POST method to a static HTML page. However, pages that are configured for the StaticFile handler do not support the POST method.
Check out the microsoft link for more explanation and possible resolution: http://support.microsoft.com/kb/942051
Close any object which is not in use (close when you are done using an object and initialize everything to null until you NEED to use it.)
This is because of an internal memory leakage in your code. As a result, it is not able to create a new object in memory.

Passing Exception Information from Global.asax to ErrorPage.aspx

I have a global error handler in Global.asax and am trying to display the exception information in a page called ErrorPage.aspx. I've read Microsoft's page about passing information between asp.net pages (http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx). I don't think any of these will work:
QueryString: I'm concerned that the length of the exception will
exceed the maximum length of the QueryString.
Post Information: The Global.asax page doesn't have any form fields.
Session State: Session state is not available in Global.asax
Public Values: I think this only works with .aspx pages
Control from Source Page: Global.asax can't have asp.net controls.
My current thought is that it would be logical to create an instance of the ErrorPage object and navigate to it (as you could do in a Windows Forms application), but I don't know how to do that or if it is possible in asp.net.
Ultimately, I'm looking for a way to display errors caught by a global error handler in a standard .aspx page. Any suggestions would be helpful.
What I would do:
Log exception information including stack trace in a log file,
Redirect to an ErrorPage with error code (regular http errorcodes + a generic 'unknown error' one + maybe some custom errors that make sense for the application) passed in query string parameter,
Display a predefined message for this error code.
There is little reason to display actual error messages to end users, more detailed error information not withstanding. If you want to display full information for debugging purposes, turn custom errors off in web.config

IIS7 Application Request Routing (arr reverse proxy) combined with managed module - time out

I am trying to build a proxy that would serve requests to an internal site (hiding the origin) but at the same time inspect the packets and asynchronously post-process them.
E.g. let's say all SOAP calls to http://www.foo.com will go to http://192.168.1.1, and at the same time be stored in a DB for post analysis. The internal server is a black box, so changing something on it is out of this question scope.
Anyway, I have configured ARR, with reverse proxy, made URL rewrite filter with wildcards, all works flawless. Then, I tried to add an managed HttpModule written in C#, and hooked to Application_BeginRequest and Application_EndRequest. I am able to access request headers, response headers on end request (app pool being in integrated mode) and even able to read response content from the outputstream by setting a filter on Response.Filter, that caches all writes in an additional memory stream.
The problem is that the moment I try to read (inside the module BeginRequest handler) the input stream from the request, ARR stays a while and throws a
HTTP Error 502.3 - Bad Gateway The
operation timed out Handler
ApplicationRequestRoutingHandler
Error Code 0x80072ee2
So it times out.
Looking with Failed Request Tracing I see:
MODULE_SET_RESPONSE_ERROR_STATUS
Warning
ModuleName="ApplicationRequestRouting",
Notification="EXECUTE_REQUEST_HANDLER",
HttpStatus="502", HttpReason="Bad
Gateway", HttpSubStatus="3",
ErrorCode="2147954402",
ConfigExceptionInfo=""
SET_RESPONSE_ERROR_DESCRIPTION Warning
ErrorDescription="The operation timed
out"
Now any similar posts on the net didn't helped as this isn't a timeout error (proxy has 120 seconds setting, page answers in under 100 ms), and the moment I comment the code of the handler that tries to read FORM data or InputStream data, everything works as a charm.
Even if I set the position of the inputstream to 0 after reading it, I still get timeouts.
If I read the input stream on EndRequest, it gets 0 bytes, even if it was a POST request. (which is clearly wrong)
Does ARR has a bug in the fact that I try to read an input stream before it tries to re-route it?
Things used: Windows Server 2008 R2
IIS 7.5 ARR v2 .Net Framework 3.5
module
Ideas?
Thanks
/Cosmin
If you can switch to .Net Framework 4, there is a solution for this.
After you are done with your BeginRequest/EndRequest in your HttpModule event handler, add a call to HttpRequest.InsertEntityBody.
/* BeginRequest event: Executes before request is processed */
private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpRequest request = application.Context.Request;
// Do something with request
DoMyOwnRequestProcessing(request);
// After you finish, make sure IIS gets the entity body
// For example, Application Request Routing needs this
request.InsertEntityBody();
}
Take a look at this on MSDN: HttpRequest.InsertEntityBody.
I know this is a year old question, but I just went through the same thing and found a solution. So, I'm posting it here for anyone else that runs into this.
In my case I only saw the timeout issue with POST requests.
It appears that the 2.0/2.1 ARR assumes that the input stream will be at the start of the posted data. However, the following code (for example) will break this assumption:
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
string value = request.Params["Name"];
The key is how Params is described
Gets a combined collection of System.Web.HttpRequest.QueryString,
System.Web.HttpRequest.Form, System.Web.HttpRequest.ServerVariables,
and System.Web.HttpRequest.Cookies items."`
When the request is a POST, accessing Params will read the posted data from the input stream, invalidating ARR's assumption. As will reading from the input stream.
I knew the data I needed was in the query string, not the posted data, so I worked around this by accessing the QueryString instead of Params. This avoids reading the posted data and works fine for me.
string value = request.QueryString["Name"];
This issue appears to be fixed in ARR 2.5.
Upgrading ARR appears to be the only solution if you need to access posted data before handing off to ARR. The key is to let HttpRequest handle acquiring the data into Params. If you read it directly it will not work.
I just ran into this bug and your experiences helped me determine the root cause.
My main server is MVC based and it looks at the Request.Form values in the Application_BeginRequest method. If the form values are accessed ARR fails to forward the body of a HTTP POST request. GET requests will work fine since there is no body.
I have routes.IgnoreRoute ("Forum/{*pathInfo}"); as a registered route but ARR runs as a HttpModule and doesn't kick-in until later in the pipeline. That means my MVC based application is given the opportunity to access the content of the POST body which somehow prevents ARR from accessing the body itself and forwarding it to the proxy'd server.
Here is Cosmin's related post on the iis.net forums: ARR 2.0 BUG - combined with managed http module timeout on read inputstream
In my application I have all myserver.com/Forum/* requests being reverse proxy'd to a separate application on another server. So I simply checked the HttpContext.Current.Request.Url in my MVC application's Application_BeginRequest method to make sure it does not contain /Forum before accessing the Request.Form values. Once I did that the POST bodies made it through ARR just fine.
UPDATE: after further testing it appears that there are still problems with ARR as POST from non-authenticated users still fails. Instead of the main website being MVC I created a dummy IIS .NET 4.0 website with a single Default.html document. But I still ran into problems with POST requests and ARR. Then I switch the application pool to ASP.NET 2.0 and what do you know, it works. At this point I have to assume that something in the .NET 4.0 pipeline is accessing the input stream which prevents ARR from accessing the input stream itself in order to forward the POST body.
按照正常来说,再iis网站界面会有一个application request
routing cache 的 icon, 可以点击 设置timeout 但是这里没有显示
找到了 官方说明可以用命令行解决这个问题
https://blogs.iis.net/richma/502-3-bad-gateway-the-operation-timed-out-with-iis-application-request-routing-arr
​
blogs.iis.net
执行以下命令,然后重启下网站服务
进入到C:\Windows\System32\inetsrv 打开管理员命令行工具执行以下命令
appcmd.exe set config -section:system.webServer/proxy /timeout:"00:00:45" /commit:apphost
重启下网站服务
我写的原文地址
https://zhuanlan.zhihu.com/p/157557980

Strange Request URLs in logged ASP.NET exceptions, but not in IIS logs

Getting unhandled exception event log messages for legitimate exceptions but the event log message includes noise in the request URL.
The noise is injected where uri escaped characters are. Noise like the apppool name, "An unhandled exception has occurred.", False and sometimes the request url itself recursively injected, sometimes a dozen times inside the url. The IIS logs don't show this injection, just the original url.
Here's one of the recursive examples:
Request URL: http://domain.com/Page.aspx?q=bransonAn unhandled exception has occurred.Chttp://domain.com/Page.aspx?q=bransonAn unhandled exception has occurred.Chttp://domain.com/Page.aspx?q=bransonAn unhandled exception has occurred.Chttp://domain.com/Page.aspx?q=branson%2C%20momomomo
The one somewhat unusual thing about the code is that it uses an exception filter which does some logging and then returns false, allowing the exception to go unhandled.
I've encountered the same issue as described above and after a few days on Google have come up with the what caused it (well for me anyway) and thought that I'd share - Even though this discussion is over a year old.
It was caused by spaces being included in the query string, which were getting changed to %20. When an exception was getting raised within the code it appears that IIS (or the Development Server in Visual Studio 2008) was, possibly, assuming that the %20 was a parameter to be passed in to the exception handler and building up the crazy looking Request URL - It was always contained 82 times within the log and no where I searched mentioned this.
In the web.config the encoding can be managed through the globalization section, but this didn't resolve our issue - It turns out that if you use RFC2396, then you don't get this issue. We're now replacing our spaces with a non-breakable space character and this is working so far in our testing.

Resources