Below sample url is given
localhost/MyPage.aspx/1582%20
asp.net throw an error saying that this page does not exist and as far as I know it is because of the %20 at the end of the URL.
the error is being caught by Application_Error in Global.asax, however I would like this to be redirected to a page and I would also like my Application_Error to log the errors, no page redirection
Are there other events in Global.asax that I can use to handle this redirection? I tried PreSendRequestHeaders but still it goes to Application_Error
Thanks.
No, you can't as there is only one event for such situation and it is Application_Error (event handlers in Global.asax are for HttpApplication).
But you can implement an IHttpModule, parse the url in it, and if it is correct, redirect your user to target page (see also here).
You should remember that, by default, not all the requests are sent to the such modules, so you might have register your module in web.config by various way:
Classic Mode
<configuration>
<system.web>
<httpModules><add name="HelloWorldModule" type="HelloWorldModule"/></httpModules>
</system.web>
</configuration>
Integrated Mode
<configuration>
<system.webServer><modules><add name="HelloWorldModule" type="HelloWorldModule"/></modules></system.webServer>
</configuration>
HTTP Handlers and HTTP Modules Overview
Related
Some bots are requesting URLs like www.example.com/test-</p><p>they-are-angry... which is creating A potentially dangerous exception in my asp.net application.
I need to validate the HttpContext.Current.Request.RawUrl in Application_BeginRequest event of Global.asax.cs file and if it is invalid I will redirect to another error page.
I do NOT want to set validateRequest="false" or requestValidationMode="2.0" but want to redirect to a particular error page if Request.RawUrl is invalid.
How to achieve this? Is there any Asp.Net predefined method to validated this URL?
Any help is highly appreciated!
If you want to just redirect to an error page, you can simply configure customErrors or implement global error handlers as detailed in existing post and on MSDN.
However, if you want to delay validation until later, such as Application_BeginRequest, you can disable request validation and invoke it explicitly, as mentioned in Imran's blog:
1. set requestValidationMode="2.0"
2. invoke Request.ValidateInput()
protected void Application_BeginRequest()
{
Request.ValidateInput();
var q = Request.QueryString;
}
I have a site which has a start up page called Test.htm. The site is temporarily down and we want to display an error page when the site loads. I have a page called error.htm. How is this possible ??
Thanks in advance!
ASP.NET provides three main methods that allow you to trap and respond to errors when they occur: Page_Error, Application_Error, and the application configuration file (Web.config).
1.The Page_Error event handler provides a way to trap errors that occur at the page level
2.You can use the Application_Error event handler to trap errors that occur in your application
3.If you do not call Server.ClearError or trap the error in the Page_Error or Application_Error event handler, the error is handled based on the settings in the section of the Web.config file.
In the section, you can specify a redirect page as a default error page (defaultRedirect) or specify to a particular page based on the HTTP error code that is raised.
e.g. You need to add following code in Global.asax page customErrors section to redirect the user to a custom page
<customErrors defaultRedirect="http://hostName/applicationName/errorStatus.htm" mode="On">
</customErrors>
Take it "offline"
See: IIS: Redirect ALL requests to one page?
Just a thought but have looked a response.redirect?
In ASP.NET MVC, how does response.redirect work?
You can hack your web.config to force your application into returning 404's when requested. Then override the 404 error page to be you "error" page.
<httpRuntime enable="false" />
<customErrors mode="On" defaultRedirect="~/errors/GeneralError.aspx">
<error statusCode="404" redirect="~/error.htm" />
</customErrors>
You can use the app_offline.htm page. If the asp.net find this page on root, then what ever you ask its show this page, and the site is down.
Second way, that is not bring the site down, on Application Begin Request, make the redirect to the page you like as:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
// just double check in case that htm proceed from asp.net
if(!cTheFile.EndsWith("test.htm"))
{
System.Web.HttpContext.Current.Response.Redirect("test.htm", true);
return;
}
}
Sorry for my English.
I have a strange problem.
When user click adword link, Google write tracking cookie like that
1813234232.1302674912.30.51.utmgclid=CcgezrsXjagCFcs-zAod_h2oCQ|utmccn=(not set)|utmcmd=(not set)|utmctr= CAA:89 AB0=40#B%20>:
In keyword section(utmctr) there is bad braskets, that cause request validation exception
A potentially dangerous Request.Cookies value was detected from the client (__utmz="...0=40#B%20> at System.Web.HttpRequest.ValidateCookieCollection(HttpCookieCollection cc)
Is there any way to solve this problem without turning off request validation?
Edited
I'm probably found obvious solution: write own request validation module http://jefferytay.wordpress.com/2010/04/15/creating-your-own-custom-request-validation/
By default asp.net validate and check the data for potential attacts.
You can disable this automatic validation by set validateRequest="false" ether on page
<%# Page validateRequest="false" %>
ether on web.config that affect all pages.
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
The only think that you need to check by your self after that, is if someone enters any script data to your inputs. Your inputs then need to check out when you render them on the page, and when you enter them on the database.
This question is kind of related to Handle URI hacking gracefully in ASP.NET in that it's too about how to best handle exceptions that occur during an ASP.NET request lifecycle. I've found a way to handle most exceptions gracefully, but then I've found that some exceptions occur so late in the request that there's no way to do stuff like Server.Transfer to compartementalize the whole error presentation logic into its own page.
So, I have to handle the exception inside the Application_Error event instead, and do Response.Writes and whatnot. It's ugly. I understand that in some circumstances the response stream could have already been flushed, so transferring the request isn't really an option. What I want to ask is if there's anyone who's found an elegant solution to this problem?
Also, I find it difficult to know when I can handle the exception gracefully by transferring the request to another page and not. What is the best way to find out where in the request lifecycle we're at when an exception occurs? If it occurs during the loading and rendering of a page, Page_Error will be able to handle it and I've not had a problem doing Server.Transfer there yet. But if the exception occurs either too early or too late for Page_Error to catch it and it bubbles to Application_Error, what do I do to know whether it's early or late?
If it's late in the lifecycle, I'll probably have to do Response.Write directly from Application_Error, but if it's early I can do Server.Transfer. The problem is that trying to do Server.Transfer will itself cause an exception if it's too in the request to do it.
So, is there a global enumeration or something similar that will indicate whether it's too late to do creative stuff with the response or not?
I have used this approach to catch all errors generated, either in web controls or pages. All it requires you to do is to inherit from a base class (one for pages and one for usercontrols) each page or usercontrol can implement its own HandleException method and do whatever it needs to do.
Full code here:
Transparent generic exception handling for asp.net / MOSS2007 (with code)
I think my advice for this would be to use ASP.NET Health Monitoring with WMI Events provider for the errors:
Here is a how to.
http://msdn.microsoft.com/en-us/library/ms178713.aspx
Hope this helps:
Andrew
I suggest that you use asp.net configuration to have a general error page for the unhandled exceptions. From the sample web.config
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
On the overall handler, just log the exception, and let asp.net do the redirect.
If you still want to go on with your customer approach, I suggest you look at the available asp.net source and check how it is doing that.
I generate an XML/Google sitemap on the fly using an Http Handler, so that I don't need to maintain an XML file manually.
I have mapped my Http Handler to "sitemap.xml" in my web.config like this:
<httpHandlers>
<add verb="*" path="sitemap.xml" type="My.Name.Space, MyAssembly" />
</httpHandlers>
It works nicely. Now, www.mywebsite.com/sitemap.xml sets my Http Handler into action and does exactly what I want. However, this url will do the same: www.mywebsite.com/some/folder/sitemap.xml and I don't really want that i.e. I just want to map my handler to the root of my application.
I have tried changing the "path" of my handler in my web.config to "/sitemap.xml" and "~/sitemap.xml" but neither works.
Am I missing something here?
Try adding the following to your web.config
<urlMappings enabled="true">
<add url="~/SiteMap.xml" mappedUrl="~/MyHandler.ashx"/>
</urlMappings>
This uses a little known feature of ASP.NET 2.0 called 'Url Mapping'
Following on from Kirtan suggested solution #1 you can do a workaround like follows:
public void ProcessRequest(HttpContext context) {
//Ensure that the sitemap.xml request is to the root of the application
if (!context.Request.PhysicalPath.Equals(Server.MapPath("~/sitemap.xml"))) {
//Invoke the Default Handler for this Request
context.RemapHandler(null);
}
//Generate the Sitemap
}
You might need to play with this a bit, not sure if invoking the default handler will just cause IIS to re-invoke your Handler again. Probably worth testing in Debug mode from VS. If it does just re-invoke then you'll need to try invoking some static file Handler instead or you could just issue a HTTP 404 yourself eg
//Issue a HTTP 404
context.Response.Clear();
context.Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return;
See the MSDN documentation on HttpContext.RemapHandler for more info -
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.remaphandler.aspx
2 solutions to this:
Soln #1:
You can check the request path using the Request.Url property, if the request is from the root path, you can generate the XML, else don't do anything.
Soln #2:
Put a web.config file with the following setting in every folder in which you don't want to handle the request for the sitemap.xml file.
You can, alternately, run a check in the global.asax, verify the request, and finaly re-assigning a new handler throughtout context.RemapHandler method.
The only thing is that you would´ve to implement a factory for that matter.
I would suggest you inherit the HttpApplication, and implement there the factory, but that's your call.