Search code examples
c#asp.net.netasp.net-mvc.net-4.5

Redirect to custom page in case of error without using Response.Redirect(url) in .net?


I have a asp.net 4.5 MVC web project. In web.config, I have those lines:

...
<httpErrors errorMode="DetailedLocalOnly">
      <clear />
      <error statusCode="404" path="/PageErrors/GeneralError.aspx?e=404" responseMode="ExecuteURL" />
...
</httpErrors>
...
<system.web>
   <customErrors mode="RemoteOnly" defaultRedirect="~/PageErrors/GeneralError.aspx" />
...
</system.web>

What I want is to redirect a user to the GeneralError page in case of an error occurs in function DoProcess(..) on the code behind without using Response.Redirect(url). What I tried is to raise the error manually by using the code 404 (tried other numbers instead as well) :

public void DoProcess(..)
{
   try
   {
      ...
   }
   catch(Exception ex)
   {
      //context.Response.Redirect("/Errors/GeneralError.aspx");
      throw new HttpException(404, "Error Message");
   }
}

Although it did not work, if there is really no page (in case of real 404 error), I am redirected to the custom GeneralError.aspx. Using no parameter in the exception like throw new HttpException(); did not help as well.

Why the manually raised error does not work and what should I do? Any help would be appreciated.

Edit: Below I tried, also did not help, saying " might be temporarily down or it may have moved permanently to a new web address." :

 context.Response.Clear();
 context.Response.StatusCode = 404;
 context.Response.End();

Solution

  • when testing the custom messages, are you running on a local server or is the application deployed?

    If you are running locally the RemoteOnly atrribute is your problem, as it only displays custom messages to users not running on the local web server. Changing it to On should solve your problem and if any error occurs you will be redirected to your "~/PageErrors/GeneralError.aspx"

    EDIT: To enable redirecting: <customErrors mode="On" defaultRedirect="~/PageErrors/GeneralError.aspx" />