How to use Web.config Custom errors in ASP.NET MVC?


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

What is web.config file in ASP.NET?

The config file is just a system configuration file. You can just think it as of a common file that is by default accessible through the system. Here, you can easily store some important function that can be accessed from anywhere in the project.

Web.config file is an XML-based configuration, this file utilized in an ASP.NET-based application to manage different types of settings that concerned with the configuration of our website. In this way, we will separate our application logic from configuration logic.

What is a custom error in ASP.NET?

Custom error means when error occurs at the same time of error message is displayed by user that is called custom error. If you set custom errors to Off, an in-depth status page is showed all users. If you set custom errors to on, a general page is showed all users.

Asp.net Provides three types of error modes to trace an error. That modes decide whether or not an error message is displayed in custom error remote the only mode is the default mode of displaying error messages.


Off Mode

This mode is use for displaying error messages on a local and remote server in case of an error.


RemoteOnly

This mode is use for displaying error messages on the remote server only in case of an error. By using this mode, we can show our own custom error messages page for specific errors on the remote server only.


RedirectMode

The Redirect mode is an attribute if you want to preserve the original URL without aspxerrorpath query string. By default, that was redirectMode set to ResponseRedirect, and that's why the URL gets changed when an exception occurred.

Set the redirectMode attribute to ResponseRewrite. This will keep the original URL but still display a custom page. Be attentive that ResponseRewrite is only working for .aspx, or .html files, but that was not for action methods. If you want to set action methods for different status codes, keep the ResponseRedirect change value.

The example sets different HTML files for different status codes and redirectMode to ResponseRewrite.



Example


<customerrors defaultredirect="~/500.html" mode="On" redirectmode="ResponseRewrite">
    <error redirect="~/500.html" statuscode="500" />
    <error redirect="~/404.html" statuscode="404" />
    <error redirect="~/400.html" statuscode="400" />
</customerrors>

Create 500.html, 404.html, and 400.html files at the root of the application. The above settings will keep the original URL without a query string while showing the inner content of an HTML page with the response status code 200 OK.

Example of the Custom error step by step

1) First go to the file menu -> New Project create new project After that, Click on Ok

selection

Fig: Project Select Screen

2) Select the MVC Checkbox then click on the Next button. Select web application and you will get the below display by clicking on ok button

selection

Fig: Framework selection Screen

(3) Create a simple project go to the Web.config File and write a simple below code for understanding the concept of the CustomErrors, change the mode of custom error.


<?xml encoding="utf-8" version="1.0">
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <appsettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appsettings>
  <system.web>
    <compilation debug="true" targetframework="4.7.2" />
    <httpruntime targetframework="4.7.2" />
  </system.web>
  <runtime>
    <assemblybinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentassembly>
        <assemblyidentity name="Antlr3.Runtime" publickeytoken="eb42632606e9261f" />
        <bindingredirect newversion="3.5.0.2" oldversion="0.0.0.0-3.5.0.2" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="Newtonsoft.Json" publickeytoken="30ad4fe6b2a6aeed" />
        <bindingredirect newversion="12.0.0.0" oldversion="0.0.0.0-12.0.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Optimization" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="1.1.0.0" oldversion="1.0.0.0-1.1.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="WebGrease" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="1.6.5135.21930" oldversion="1.0.0.0-1.6.5135.21930" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Helpers" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="3.0.0.0" oldversion="1.0.0.0-3.0.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.WebPages" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="3.0.0.0" oldversion="1.0.0.0-3.0.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Mvc" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="5.2.7.0" oldversion="1.0.0.0-5.2.7.0" />
      </dependentassembly>
    </assemblybinding>
  </runtime>
	<system.web>
		<customerrors mode="On"></customerrors>
	</system.web>
  <system.codedom>
    <compilers>
      <compiler compileroptions="/langversion:default /nowarn:1659;1699;1701" extension=".cs" language="c#;cs;csharp" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warninglevel="4" />
      <compiler compileroptions="/langversion:default /nowarn:41008 /define:_MYTYPE=&quot;Web&quot; /optionInfer+" extension=".vb" language="vb;vbs;visualbasic;vbscript" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warninglevel="4" />
    </compilers>
  </system.codedom>
</configuration>

</?xml>

Op zoek naar een vertrouwd ASP.Net-softwareontwikkelingsbedrijf ?

Uw zoekopdracht eindigt hier.


(4) Go to the Home controller and write a below code for understanding the concept of the CustomErrors

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BlogCustomError.Controllers
{
    public class HomeController : Controller
    {
        
        public ActionResult Index()
        {
            string msg = null;
            ViewBag.Message = M.Length; // this will throw an exception
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        
    }
}

After that go to the model folder and add new class for Error handling. Apply the name of class is “FilterConfig” and add below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BlogCustomError.Models
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

After Change the Mode setting Run the project and you will get the below output.

An error occurred while processing your request this error was written by the user. This functionality has lots of status code for different errors.

selection

Fig: Output Screen

Here you can set your own error message with statusCode. We can set default code for default error like page not found

<?xml encoding="utf-8" version="1.0">
<customerrors defaultredirect="/error" mode="On">
    <error redirect="/error/badrequest" statuscode="400" />
    <error redirect="/error/notfound" statuscode="200" />
    <error redirect="/error/internalerror" statuscode="500" />
</customerrors> 

</?xml>

This attribute is used to define an https status code which is a numeric value. You can define multiple attributes using multiple error elements.

400 Status code is call when required page not found type of error

200 Status code is call when response is ok type of error.


Status Code attribute

301 – This code is use to Moved Permanently

403 – This code is use for Forbidden

404 – This code is use for Not Found


Redirect attribute

This attribute will be used to redirect to a page designed to show messages based on a specific type of error. These specific types can be defined using the status Code.

Conclusion

This blog is used for understanding the concept of custom error. This is used to provide user define error message for specific error on the website. We hope you liked this article on Custom Error, this blog is helpful to you as we have covered about all factors of Custom Error. Main purpose of custom error is to provide the simple understandable error message application.

How to use Web.config Custom errors in ASP.NET MVC?

What is web.config file in ASP.NET?

The config file is just a system configuration file. You can just think it as of a common file that is by default accessible through the system. Here, you can easily store some important function that can be accessed from anywhere in the project.

Web.config file is an XML-based configuration, this file utilized in an ASP.NET-based application to manage different types of settings that concerned with the configuration of our website. In this way, we will separate our application logic from configuration logic.

What is a custom error in ASP.NET?

Custom error means when error occurs at the same time of error message is displayed by user that is called custom error. If you set custom errors to Off, an in-depth status page is showed all users. If you set custom errors to on, a general page is showed all users.

Asp.net Provides three types of error modes to trace an error. That modes decide whether or not an error message is displayed in custom error remote the only mode is the default mode of displaying error messages.


Off Mode

This mode is use for displaying error messages on a local and remote server in case of an error.


RemoteOnly

This mode is use for displaying error messages on the remote server only in case of an error. By using this mode, we can show our own custom error messages page for specific errors on the remote server only.


RedirectMode

The Redirect mode is an attribute if you want to preserve the original URL without aspxerrorpath query string. By default, that was redirectMode set to ResponseRedirect, and that's why the URL gets changed when an exception occurred.

Set the redirectMode attribute to ResponseRewrite. This will keep the original URL but still display a custom page. Be attentive that ResponseRewrite is only working for .aspx, or .html files, but that was not for action methods. If you want to set action methods for different status codes, keep the ResponseRedirect change value.

The example sets different HTML files for different status codes and redirectMode to ResponseRewrite.



Example


<customerrors defaultredirect="~/500.html" mode="On" redirectmode="ResponseRewrite">
    <error redirect="~/500.html" statuscode="500" />
    <error redirect="~/404.html" statuscode="404" />
    <error redirect="~/400.html" statuscode="400" />
</customerrors>

Create 500.html, 404.html, and 400.html files at the root of the application. The above settings will keep the original URL without a query string while showing the inner content of an HTML page with the response status code 200 OK.

Example of the Custom error step by step

1) First go to the file menu -> New Project create new project After that, Click on Ok

selection

Fig: Project Select Screen

2) Select the MVC Checkbox then click on the Next button. Select web application and you will get the below display by clicking on ok button

selection

Fig: Framework selection Screen

(3) Create a simple project go to the Web.config File and write a simple below code for understanding the concept of the CustomErrors, change the mode of custom error.


<?xml encoding="utf-8" version="1.0">
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <appsettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appsettings>
  <system.web>
    <compilation debug="true" targetframework="4.7.2" />
    <httpruntime targetframework="4.7.2" />
  </system.web>
  <runtime>
    <assemblybinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentassembly>
        <assemblyidentity name="Antlr3.Runtime" publickeytoken="eb42632606e9261f" />
        <bindingredirect newversion="3.5.0.2" oldversion="0.0.0.0-3.5.0.2" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="Newtonsoft.Json" publickeytoken="30ad4fe6b2a6aeed" />
        <bindingredirect newversion="12.0.0.0" oldversion="0.0.0.0-12.0.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Optimization" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="1.1.0.0" oldversion="1.0.0.0-1.1.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="WebGrease" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="1.6.5135.21930" oldversion="1.0.0.0-1.6.5135.21930" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Helpers" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="3.0.0.0" oldversion="1.0.0.0-3.0.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.WebPages" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="3.0.0.0" oldversion="1.0.0.0-3.0.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Mvc" publickeytoken="31bf3856ad364e35" />
        <bindingredirect newversion="5.2.7.0" oldversion="1.0.0.0-5.2.7.0" />
      </dependentassembly>
    </assemblybinding>
  </runtime>
	<system.web>
		<customerrors mode="On"></customerrors>
	</system.web>
  <system.codedom>
    <compilers>
      <compiler compileroptions="/langversion:default /nowarn:1659;1699;1701" extension=".cs" language="c#;cs;csharp" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warninglevel="4" />
      <compiler compileroptions="/langversion:default /nowarn:41008 /define:_MYTYPE=&quot;Web&quot; /optionInfer+" extension=".vb" language="vb;vbs;visualbasic;vbscript" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warninglevel="4" />
    </compilers>
  </system.codedom>
</configuration>

</?xml>

Op zoek naar een vertrouwd ASP.Net-softwareontwikkelingsbedrijf ?

Uw zoekopdracht eindigt hier.


(4) Go to the Home controller and write a below code for understanding the concept of the CustomErrors

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BlogCustomError.Controllers
{
    public class HomeController : Controller
    {
        
        public ActionResult Index()
        {
            string msg = null;
            ViewBag.Message = M.Length; // this will throw an exception
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        
    }
}

After that go to the model folder and add new class for Error handling. Apply the name of class is “FilterConfig” and add below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BlogCustomError.Models
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

After Change the Mode setting Run the project and you will get the below output.

An error occurred while processing your request this error was written by the user. This functionality has lots of status code for different errors.

selection

Fig: Output Screen

Here you can set your own error message with statusCode. We can set default code for default error like page not found

<?xml encoding="utf-8" version="1.0">
<customerrors defaultredirect="/error" mode="On">
    <error redirect="/error/badrequest" statuscode="400" />
    <error redirect="/error/notfound" statuscode="200" />
    <error redirect="/error/internalerror" statuscode="500" />
</customerrors> 

</?xml>

This attribute is used to define an https status code which is a numeric value. You can define multiple attributes using multiple error elements.

400 Status code is call when required page not found type of error

200 Status code is call when response is ok type of error.


Status Code attribute

301 – This code is use to Moved Permanently

403 – This code is use for Forbidden

404 – This code is use for Not Found


Redirect attribute

This attribute will be used to redirect to a page designed to show messages based on a specific type of error. These specific types can be defined using the status Code.

Conclusion

This blog is used for understanding the concept of custom error. This is used to provide user define error message for specific error on the website. We hope you liked this article on Custom Error, this blog is helpful to you as we have covered about all factors of Custom Error. Main purpose of custom error is to provide the simple understandable error message application.

  • Pin It
TOP