I've got the following error when I have : in url address:
A potentially dangerous Request.Path value was detected from the client (:)
I want when my application get an error I can redirect to /Error/NotFound action but sometimes it doesn't happen.
For example, I have below code for handle custom errors and it works properly but when I have a potentially dangerous error controller.Execute() doesn't fire.
protected void Application_Error()
{
var lastException = Server.GetLastError();
if (lastException.GetType() != typeof(HttpException))
return;
var httpException = lastException as HttpException;
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException?.GetHttpCode() == 404 || httpException?.GetHttpCode() == 400)
routeData.Values.Add("action", "NotFound");
if (routeData.Values.Count <= 1)
return;
try
{
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
throw new NullReferenceException();
}
}
I realize that when a potentially dangerous error occurred some property of my context such as CurrentNotification, Handler, Items, Profile, Session and User is null. I don't know exactly my context is related to this problem or not.
And here is my webconfig:
<system.web>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" maxRequestLength="314572800" enableVersionHeader="false" requestPathInvalidCharacters="<,>,%,&,:,\,?" />
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
</httpErrors>
</system.webServer>
you can handle all types of errors in your Web.Config like this :
<customErrors mode="On" defaultRedirect="~/Error/ErrorPage/404" >
<error statusCode="404" redirect="~/Error/ErrorPage/404" />
<error statusCode="403" redirect="~/Error/ErrorPage/403" />
<error statusCode="500" redirect="~/Error/ErrorPage/500" />
</customErrors>
what i added is the
defaultRedirect
to handle any type of errors
Related
How to show a custom error page when an application error occurred without changing the url?
When application error occurs, then how to show customer a custom error page without routing to another Url?
Inside your web.config check that the configuration looks like:
<system.web>
...
<customErrors mode="On">
<error statusCode="404" redirect="~/custom404.html"/>
<customErrors
</system.web>
<customErrors mode="On" defaultRedirect="~/custom404.html">
</customErrors>
You can do this in code too. For a MVC project one can ovverride the Controller's function OnException, perform some logging and other stuff then load the contents from an Error.URL in background where the error information is formated.
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext != null && filterContext.Exception != null && !filterContext.ExceptionHandled)
{
ViewBag.Exception = filterContext.Exception;
filterContext.Result = View("~/Views/Shared/Error.cshtml");
filterContext.ExceptionHandled = true;
Log.Error(filterContext.Exception.Message +":" + filterContext.Exception.StackTrace);
}
}
In this snippet all Controllers in the project inherit from a BaseController where the function OnException is being overridden.
Try this in your Web.config file
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/errors/error">
</customErrors>
In any error it will redirect to the /errors/error page. Please note the redirectMode attribute. With the value ResponseRewrite the url will not change.
Now, if you want to show a different page for a specific error, you can set it with the following.
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/errors/error">
<error statusCode="404" redirect="/errors/error404" />
<error statusCode="500" redirect="/errors/error500" />
</customErrors>
For some reason, when entering a dud URL to a file/directory/controller that does not exist, the following error is thrown:
System.Web.HttpException
The controller for path '' was not found or does not implement IController
System.Web.Mvc.IController > GetControllerInstance(System.Web.Routing.RequestContext, System.Type)
IIS then follows the regular error handling and shows the page appropriate for a 500 Internal Server Error. A 404 Not Found error handling logic should be followed. Another web application I am testing on DOES NOT throw this HttpException when it can't find a route, and returns 404 normally. So what triggeres this HttpException?
Why and how to follow a 404 route for this type of error instead of a 500? Below is the configuration of the error handling. No other code is handling errors. So why is the 500 error always shown. It's as if the default handling handles the 'can't find controller' exception as an error when in fact it's a not-found.
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace" defaultPath="/StaticErrors/Default.html" defaultResponseMode="ExecuteURL">
<clear />
<error statusCode="404" path="/mvcError/Http404" responseMode="ExecuteURL" />
<error statusCode="500" path="/mvcError/Http500" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
<system.web>
<customErrors defaultRedirect="/StaticErrors/Default.html" mode="On" redirectMode="ResponseRewrite">
<error redirect="/mvcError/Http404" statusCode="404" />
<error redirect="/mvcError/Http500" statusCode="500" />
</customErrors>
</system.web>
Failed Request Trace shows this. Basically since no route is round, the HttpException is thrown, and the 500 route handling kicks in, instead of a 404. I'm not doing anything to overide any normal default behaviour. The HandleErrorAttribute is not being added either to the MVC filters.
You should add a filter controller to override some IIS custom error.
public class mvcErrorController : Controller
{
public ActionResult Http404()
{
Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
return View();
}
}
You need to remove the
redirectMode="ResponseRewrite"
Option from you customErrors tag. Unfortunately, this does mean you will have a 302 before your 404, but it will fix your issue.
Alternatively, use ASPX pages for your error pages:
<customErrors defaultRedirect="/StaticErrors/Default.html" mode="On" redirectMode="ResponseRewrite">
<error redirect="/StaticErrors/Http404.aspx" statusCode="404" />
<error redirect="/StaticErrors/Http500.aspx" statusCode="500" />
</customErrors>
There is previous discussion on this issue on SO here
I have the following code inside my action methods:-
public ActionResult ManageCustomerVLANs(string customerName)
{
if (!repository.IsCustomerExsists(customerName))
{
throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
}
And I have defined the following inside my web.config, to handle any 404 http code:-
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="NoCache" noStore="true" duration="0" varyByParam="*"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<!--<customErrors mode="RemoteOnly"/>-->
<customErrors mode="RemoteOnly">
<error statusCode="404" redirect="~/Home/" />
</customErrors>
But currently if the action method return “throw new HttpException”, nothing is actually returned and the execution will continue after this “throe new HttpException”.
so can anyone advice, how I can return an http 404 ?
You can return 404 like this.
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
I have a relatively untouched MVC4 project with the following in my Web.Release.config:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
</system.web>
It's not working though - I get normal error pages when in Release mode.
If I place that code in my Web.Config, it works as expected. I only want this applied when in Release though.
I also tried this in web.release.config:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error" xdt:Transform="Replace">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
<compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>
To no avail.
Why would this be happening?
UPDATE: If I use the following in my global.asax:
void Application_Error(object sender, EventArgs e)
{
#if DEBUG
#else
Response.Redirect("/Error");
#endif
return;
}
I get the desired behavior. I feel like I should be able to use the web.config settings only though... so I'd like to leave this open.
The problem is you're not publishing. The web.release.config file is only transformed during publish as far as I know. If you're just building and running locally that file won't be used.
Also in your Application_Error you should get the status code for the error. Something like
var exception = Server.GetLastError();
var httpException = exception as HttpException;
if (httpException != null)
{
if (httpException.GetHttpCode() == 404)
RedirectToMyNotFoundPage();
}
Otherwise you will basically just handle all errors, which may or may not be what you want to do.
If you want to handle MvcErrors, and get the controller/action that the exception occured in, you should look into Filters.
Here's a good article on error filtering if that's what you're going for.
http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx
in web.config code is
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>
-->
<forms loginUrl="Login.aspx" cookieless="UseCookies">
</forms>
</authentication>
whenever iam closing application and logging back user remains in and ask me to log out.. i want to make sure whenever application starts it should not be logged in previously..
this is web.config code..
<authentication mode="Forms">
<!--
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>
-->
<forms loginUrl="Login.aspx" cookieless="UseCookies">
</forms>
</authentication>
<authorization>
<allow roles="Administrator,Attorney,Director of Operations,Office Manager,Paralegal,Partner,Processor,Salary Admin,Unit Manager"/>
<deny users="?"/>
</authorization>
<pages>
</pages>
</system.web>
Login button code
string [] arr = new string[10];
bool bCheckUser;
try
{
if ((txtUserName.Text == "") || (txtPassword.Text == ""))
{
lblError.Visible = true;
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = "Enter UserName and Password";
}
else
{
bCheckUser = Membership.ValidateUser(txtUserName.Text, txtPassword.Text);
arr = Roles.GetRolesForUser(txtUserName.Text);
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text);
if (bCheckUser == true)
{
lblError.Visible = false;
Response.Redirect("MainMenu.aspx");
}
else
{
lblError.Visible = true;
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = "You Username or Password is Invalid. Please try Again";
}
}
}
catch(Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
You are passing true to this method that is to create persistent cookies:
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
pass false instead and also move that inside of if block and remove that redirect if you don't want hard redirect:
if (bCheckUser == true)
{
lblError.Visible = false;
// Response.Redirect("MainMenu.aspx");
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
}
Or use SetAuthCookie method like below:
if (bCheckUser == true)
{
lblError.Visible = false;
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
Response.Redirect("MainMenu.aspx");
}
Edit:
It looks like you are calling FormsAuthentication.RedirectFromLoginPage regardless of whether Membership.ValidateUser returns true or false. That might have something to do with it. Is this code being called in the Page_Load of your login page?
A couple of questions I have for you:
Are you actually closing the browser
and then reopening it, or just
returning to your site after
receiving an error in the same
browser?
Does your login page have a Remember
Me setting?
Have you restricted access to your
webpages in your webconfig?
By default I think the webconfig leaves most pages open. You'll need an authorization section to restrict access.
<authorization>
<deny users="?" />
</authorization>
Here's some links to check out as well:
http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html
http://www.asp.net/security/tutorials/an-overview-of-forms-authentication-vb