Latest Entries »

Pattern Layout Converter is the way you tell log4net how to log something that it doesn’t know yet.

You first create your class that will get the information, for instance, this class will is to log the machine name:

using System;
using System.IO;
using log4net.Layout.Pattern;

namespace MyApplication.Logging
{
    public class MachinePatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            writer.Write(Environment.MachineName);            
        }
    }
}

Then, you edit your config file adding the converter you just created:

  <log4net>
    <appender name="Application" type="log4net.Appender.FileAppender">
      <file value="log\application.log" />
      <appendToFile value="true" />
      <maximumFileSize value="1024KB" />
      <layout type="log4net.Layout.PatternLayout">        
        <converter>
          <name value="machine" />
          <type value="MyApplication.Logging..MachinePatternConverter" />
        </converter>        
        <conversionPattern value="%date [%thread] %level %logger %machine - %message e:%exception%newline %newline" />
      </layout>
    </appender>
<!-- lines removed for brevity -->

In the code above, we added our new converter and named it “machine”. Then, In the conversionPattern line, we can use it wherever we want by adding the %machine variable.

Here are others converters you may want to use:

    public class IPPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (HttpContext.Current != null)
            {
                writer.Write(HttpContext.Current.Request.UserHostAddress);
            }
        }
    }

    public class UrlPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (HttpContext.Current != null)            
                writer.Write(HttpContext.Current.Request.Url.AbsoluteUri);
        }
    }

    public class UserAgentPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (HttpContext.Current != null)
            {
                writer.Write(HttpContext.Current.Request.UserAgent);
            }
        }
    }

Now, applying all converter in our config file:

  <log4net>
    <appender name="Application" type="log4net.Appender.FileAppender">
      <file value="log\application.log" />
      <appendToFile value="true" />
      <maximumFileSize value="1024KB" />
      <layout type="log4net.Layout.PatternLayout">
        <converter>
          <name value="url" />
          <type value="MyApplication.Logging.UrlPatternConverter" />
        </converter>
        <converter>
          <name value="ip" />
          <type value="MyApplication.Logging.IPPatternConverter" />
        </converter>
        <converter>
          <name value="machine" />
          <type value="MyApplication.Logging.MachinePatternConverter" />
        </converter>
        <converter>
          <name value="userAgent" />
          <type value="MyApplication.Logging.UserAgentPatternConverter" />
        </converter>
        <conversionPattern value="%date [%thread] %level %logger %url %ip %machine %userAgent - %message e:%exception%newline %newline" />
      </layout>
    </appender>

Do you have any interest Pattern Layout Converter you use in your application?

Logging to multiple files – Log4Net

I am going to explain how to log using Log4Net and how to separate the different types of logs from your application into different output files. The main focus of this post is not explain how log4net works in detail, however if your are interesting about learning more about it I recommend this article http://www.codeproject.com/KB/dotnet/Log4net_Tutorial.aspx.

The purpose here is to separate the log by source, for instance, caching log in one file, queries in another file, application log in another one, and also a single file for logging errors from all sources, this way we can find errors easier. The errors will still be logged in the library’s log though, because we may want to focus on that library specifically.

Take a look at this configuration file and will explain where the separation comes up later:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="Application" type="log4net.Appender.FileAppender">
    <file value="log\application.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
    <file value="log\error.log" />
    <rollingStyle value="Date" />
    <appendToFile value="true" />
    <datePattern value="ddMMyyyy" />
    <maxSizeRollBackups value="10" />
    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="ERROR"/>
    </filter>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>

  </appender>

  <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <bufferSize value="1" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="data source=127.0.0.1;initial catalog=Application_Log_Database;integrated security=false;persist security info=True;User ID=abc123;Password=abc123" />
    <!-- AppId parameter comes from the table Applications -->
    <commandText value="INSERT INTO application_log ([date],[thread],[level],[logger], [message], [exception]) VALUES (@log_date,@thread,@log_level,@logger, @message,@exception)" />

    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="ERROR"/>
      <levelMax value="FATAL"/>
    </filter>

    <parameter>
      <parameterName value="@log_date" />
      <dbType value="DateTime" />
      <layout type="log4net.Layout.RawTimeStampLayout" />
    </parameter>

    <parameter>
      <parameterName value="@thread" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@log_level" />
      <dbType value="String" />
      <size value="50" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@logger" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@message" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@exception" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.ExceptionLayout" />
    </parameter>    

  </appender>

  <appender name="OpenRasta" type="log4net.Appender.FileAppender">
    <file value="log\openrasta.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="Messaging" type="log4net.Appender.FileAppender">
    <file value="log\messaging.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="Queries" type="log4net.Appender.FileAppender">
    <file value="log\queries.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="Memcached" type="log4net.Appender.FileAppender">
    <file value="log\memcached.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="All" />
    <appender-ref ref="ErrorLog" />
    <appender-ref ref="AdoNetAppender" />
  </root>

  <logger name="Log4NetExample">
    <level value="INFO" />
    <appender-ref ref="Application" />
  </logger>

  <logger name="OpenRasta">
    <level value="INFO" />
    <appender-ref ref="OpenRasta" />
  </logger>

  <logger name="Spring">
    <level value="WARN" />
    <appender-ref ref="Messaging" />
  </logger>
  <logger name="NServiceBus">
    <level value="WARN" />
    <appender-ref ref="Messaging" />
  </logger>

  <logger name="System.Data.Linq">
    <level value="DEBUG" />
    <appender-ref ref="Queries" />
  </logger>

  <logger name="Enyim.Caching.Memcached">
    <level value="WARN" />
    <appender-ref ref="Memcached" />
  </logger>

</log4net>

Don’t be scared! It may look big, but that is because I’m showing a configuration with a lot of libraries and the AdoNetAppender is a little big too. What this configuration is doing is creating the Appenders, setting the root section, and then setting the level things will be logged with the loggers section.

The Appenders are most of them logging into text files, and one is logging into the database. In order to have the errors from all sources, notice we are adding the ErrorLog appender and the AdoNetAppender in the root section. This is because all the loggers must inherit those two. All the loggers will log their errors in a text file and in the database:

<root>
	<level value="All" />
	<appender-ref ref="ErrorLog" />
	<appender-ref ref="AdoNetAppender" />
</root>

The root’s log level is set to “All“, so if you don’t specify any level to a logger, it will inherit from the root and its value will be All as well.

If you look at those two appenders we are filtering their minimum level types as ERROR in the appender itself.

<appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">    
	<filter type="log4net.Filter.LevelRangeFilter">
	  <levelMin value="ERROR"/>
	</filter>
...

This is how we carry the error loggers along with the other loggers but logging only the errors. The libraries are filtered by their namespace, for instance Enyim.Caching.Memcached, and each library has its own logger set with a specific level of logging.

Log4net is a well known library and most of other libraries support it by default. For those libraries that doesn’t, for example, LinqToSql, a quick search on Google can give you the code to make it supported.

When you get data using LinqToSql and change something in the object, you expect that calling get object again will invalidate the cache and return the new objects, but it doesn’t! LinqToSql will return a reference of the object, what means, it will return the same object you had before.

The code below force LinqToSql to get new object(s), not the one(s) it has in memory:

public Order Get(int id)
{
	var order = Context.Orders.SingleOrDefault(o => o.orderId == id);
	
	if (order != null)
		// invalidate cache
		Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, order);

	return order;
}

Continuing my posts about configuration files, now I’m going to show you how to work with a list of items.

Here is the xml:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <enabled>true</enabled>
  <name>Example text name</name>
  <hosts>
    <host ip="127.0.0.1" port="80" username="test" password="pass" />
    <host ip="172.168.0.1" port="80" username="test2" password="pass2" />
  </hosts>
</main>

Is basically the same xml file I was using in the previous post but now hosts is a list and not only a single entry.

So, let’s see how we handle it in our code:

[XmlRoot("main")]
public class ModelExampleConfiguration
{
    public ModelExampleConfiguration()
    {
        this.Hosts = new List<HostConfiguration>();
    }
        
    [XmlElement("enabled")]
    public bool Enabled { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlArray("hosts")]
    [XmlArrayItem("host")]
    public List<HostConfiguration> Hosts { get; set; }
}

This is important! Note that the list had to be instantiated in the constructor so that the .NET can add the items into the list. Also, it was used to new attributes: XmlArray and XmlArrayItem. The first one defines the name of the list, and the second the name of the items of the list.

You might also need a list where you don’t have a parent item. Let’s see an example:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <enabled>true</enabled>
  <name>Example text name</name>
  <hosts>
    <host ip="127.0.0.1" port="80" username="test" password="pass" />
    <host ip="172.168.0.1" port="80" username="test2" password="pass2" />
  </hosts>
  <users groupName="admin">
    <user name="user1" />
    <user name="user2" />
  </users>
  <users groupName="guests">
    <user name="user3" />
    <user name="user4" />
  </users>
</main>

I add those two groups of users and each group of user has a list of users. Our full code then will look like:

using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [XmlRoot("main")]
    public class ModelExampleConfiguration
    {
        public ModelExampleConfiguration()
        {
            this.Hosts = new List<HostConfiguration>();
        }
        
        [XmlElement("enabled")]
        public bool Enabled { get; set; }

        [XmlElement("name")]
        public string Name { get; set; }

        [XmlArray("hosts")]
        [XmlArrayItem("host")]
        public List<HostConfiguration> Hosts { get; set; }

        [XmlElement("users")]
        public UserGroupConfiguration[] UserGroup { get; set; }
    }

    public class HostConfiguration
    {
        [XmlAttribute("ip")]
        public string IP { get; set; }

        [XmlAttribute("port")]
        public int Port { get; set; }

        [XmlAttribute("username")]
        public string Username { get; set; }

        [XmlAttribute("password")]
        public string Password { get; set; }
    }

    public class UserGroupConfiguration
    {
        [XmlAttribute("groupName")]
        public string GroupName { get; set; }

        [XmlElement("user")]
        public UserConfiguration[] Users { get; set; }
    }

    public class UserConfiguration
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
    }
}

See that now I used an array instead of a generic list. I could have used the list as well, but I think that way is simpler.

I’m currently working in a project where one need is to create easy customizable configuration files. The interest part comes when we need to read these configuration files and parsing them to .NET classes.

As I myself had to look up how some attributes work, I decided to share my experience creating those files, so this might help someone else going through the same problems.

To start off, let’s have a simple xml:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <enabled>true</enabled>
  <name>Example text name</name>
  <host ip="127.0.01" port="80" username="test" password="pass" />
</main>

Now the our model class:

using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [XmlRoot("main")]
    public class ModelExampleConfiguration
    {
        [XmlElement("enabled")]
        public bool Enabled { get; set; }

        [XmlElement("name")]
        public string Name { get; set; }

        [XmlElement("host")]
        public HostConfiguration Host { get; set; }
    }

    public class HostConfiguration
    {
        [XmlAttribute("ip")]
        public string IP { get; set; }

        [XmlAttribute("port")]
        public int Port { get; set; }

        [XmlAttribute("username")]
        public string Username { get; set; }

        [XmlAttribute("password")]
        public string Password { get; set; }
    }
}

Note: If you have your class and property names exactly like your config file then you don’t need to specify the attributes, but I just prefer to always use them, this way I can name my classes however I want.

Notice I’m handling both elements and attributes, using XmlElement and XmlAttributes.

Now, the code to parse the xml into a model class:

using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var reader = XmlReader.Create("Example.xml");

            var factory = new XmlSerializerFactory();
            var serializer = factory.CreateSerializer(typeof(ModelExampleConfiguration));
            var config = serializer.Deserialize(reader) as ModelExampleConfiguration;
        }
    }
}

// config.Enabled will output true
// config.Host.Username will output test

In the next post I’ll show how to deserialize a list / array of items.

I know I’ve been posting only videos lately but this one deserves to be here too and I really don’t think videos are bad. Instead of reading and just listen to your mind you can watch the person talking, acting and see their personality.

In this two videos, the astonish Paul Irish tells us 10 things he learned from the jQuery Source and then 11 more things he learned from it. At first, when we look at the jQuery Source it looks scary and huge, but Paul Irish diggs in it and shows us that we can learn many things straight from the source, instead of looking for docs on the internet.

I personally already did this long time ago and I recommend to do it. It’s really like a wiki of javascript codes.

and here is the other

Click here to see the post in his blog.

Stephen Walther from the ASP.NET Team joins James Senior (@jsenior) on Web Camps TV to discuss an exciting announcement: Microsoft is making their first contributions to the jQuery open source project!
In the past 6 months, they’ve been busy working on three features:

  1. Templating
  2. Data-Linking
  3. Globalization

In this video, they show demos of the contributions in action, take a look:

Web Camps TV #6 - Microsoft Commits Code to jQuery!

Great speech from Scott Hanselman that shows us how we can be better developers using social networking and he proposes that every developer needs a blog.

 How to be a better developer through social media

Scott gave an advice I really liked it. He says "Remember, we are all immature!". If you think like that you will feel more confident to write something out there. You don’t need to feel afraid of not writing the best code. Just go and say: "Here it is. Here’s my code, I’m learning". Let it roll.

What motivates developers?

This is an animation like video that talks about how people feel rewarded and what motivates them to do a better job at work. It also shows how it relates to open source.

How to use CustomErrors in ASP.NET MVC 2

First, let’s see how our Web.config file will look like and after that I will show you how to create the pages.

<customErrors mode="On" defaultRedirect="~/Error">
  <error statusCode="404" redirect="~/Error/NotFound"/>
  <error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>

I’m going to show the steps to make it work for those three types of errors and also explain you about the HandleError attribute and how it handles the information specified in the customErrors. I’m also putting here the code I wrote in order to handle the AccessDenied error.

Error Page

When we are talking about the Error Page, one thing that you should understand is that without the HandleError Attribute, if an error occurs the .NET will just redirect the user to the page you specified in your Web.Config. So, if you have the “defaultRedirect” property pointing to something like “~/GenericError.aspx”, the GenericError.aspx page under the root folder of your project will be shown without any information about the Error. It could be a static HTML page that only tells the user “Hey, you’ve got an Error”.

Now, if you what you want is to show the user some information about the error, like the description or even the stackTrace but with the page looking like your default theme, then you can use the HandleError Attribute. By applying it to a Controller or a method the behavior of the customErrors changes a little bit. Instead of just pointing to some page, the exception handling will render a View, more specifically, a view called Error (if you don’t specify any other name to the Attribute) it doesn’t matter what name you’ve told the “defaultRedirect” to take you to. Along with that, it will send a HandleErrorInfo model containing the Controller name where the exception occurred, the Action name and the exception itself, so you can get the stackTrace and the description of the error.

Although it might seem obvious for some what the HandleError attribute does I’ve seen it’s a common issue people setting their customErrors to show something like GenericError.aspx and using the HandleError attribute. Or even, setting the defaultRedirect property to “Error” and expecting the Index method within the ErrorController to receive a HandleErrorInfo parameter. Remember, when using the HandleError attribute, the “Error“ View will be rendered internally, without even getting into the ErrorController.

Common mistake

Web.Config

<customErrors mode="On" defaultRedirect="Error/Ops" />

HomeController.cs

[HandleError] // using HandleError attribute
public class HomeController : Controller
{
    public ActionResult Index()
    {
		return View();
    }
}

ErrorController.cs

public class ErrorController : Controller
{
    public ActionResult Ops()
    {
        //
		// Wrong! It won't get here because
		// the HandleError will handle the error.
		return View();
    }
}

The right way

I’m going to demonstrate now how you can make it work with a page that shows some information about the error. With this example, even though someone forget using the HandleError attribute, a friendly page still shows up but without the error info (it’s better than not showing anything). It could be improved, off course, but that it’s another point.

Web.config

<customErrors mode="On" defaultRedirect="Error" />

Error.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>

<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Error
</asp:Content>

<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">       

    <h2>
        Sorry, an error occurred while processing your request.
    </h2>

	<% if (Model.Exception != null ) { %>
		<p>
		  Controller: <%= Model.ControllerName %>
		</p>
		<p>
		  Action: <%= Model.ActionName %>
		</p>
		<p>
		  Message: <%= Model.Exception.Message%>
		</p>
		<p>
		  Stack Trace: <%= Model.Exception.StackTrace%>
		</p>
	<% } %>
</asp:Content>

Place that page inside your Views folder. It can be either your Shared or Error folder. The name must be Error.aspx.

That’s it! Only the aspx file and the setting inside the Web.config.

Only if you want that whether the Controller have or not the HandleError attribute, your custom error page will still be shown, then you can add an action method into your ErrorController:

ErrorController.cs

public class ErrorController : Controller
{
    public ActionResult Index()
    {
		return View("Error");
    }
}

Now whether the page is being redirected to the defaultRedirect or rendered by the HandleError, the page will always be called.

To force an error, let’s create a code that throws an exception inside the Index of the HomeController:

int a = 0;
int b = 0;
int result = a / b;

That will throw the DivideByZeroException, see the friendly page in action:

CustomErrros Error Handling

 

404 NotFound Page

For the Not Found page we don’t have much to tell the user, so there is not much to do. It’s only the redirect to a page and, the information we can show is the wrong path. That information already comes as a query string.

Just to centralize the error handling and make it more organized, let’s put our NotFound within our ErrorController. So, add your the following method to the ErrorController:

public ActionResult NotFound(string aspxerrorpath)
{
	ViewData["error_path"] = aspxerrorpath;

	return View();
}

and the aspx page code:

NotFound.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Not Found
</asp:Content>

<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Sorry, the page <%: ViewData["error_path"] %> does not exist.
    </h2>    
</asp:Content>

and add the following line for the Not Found error into your customErrors section:

<customErrors mode="On" defaultRedirect="Error">
  <error statusCode="404" redirect="Error/NotFound"/>
</customErrors>

See the result:CustomError Page Not Found

 

403 AccessDenied

Most of the times when someone doesn’t have access to a page it’s only a login issue. But there are also times that a user has logged in but they are allowed to see something or perform some task, maybe because the lack of sufficient privileges. I’m going to show here how to handle those type of errors and the way I do that is by creating an ActionFilter attribute that you can put on a class or a method.

I’m going to hide some code for clarity:

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

namespace ErrorHandling.Controllers
{
    public class AuthorizationAttribute : ActionFilterAttribute, IExceptionFilter
    {
        public string Action { get; set; }
        
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //
            // check permissions

            if (accessDenied)
            {
                throw new System.Web.HttpException((int)System.Net.HttpStatusCode.Forbidden,
                        "You are now allowed to see this page.");
            }

            base.OnActionExecuting(filterContext);
        }

        #region IExceptionFilter Members

        // this method is almost a clone of HandleErrorAttribute from MVC
        // it's just changed so that we take the error message to the page set in the <customErrors>
        public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
                return;

            Exception exception = filterContext.Exception;

            // If this is not an HTTP 403 (for example, if somebody throws an HTTP 500 from an action method),
            // ignore it.
            if (new HttpException(null, exception).GetHttpCode() != 403)
            {
                return;
            }

            // try to get the customError page for the 403 code
            string customErrorPage = GetCustomError("403");

            // if there isn't a redirect to a 403 error page then get out
            if (customErrorPage == null)
                return;

            filterContext.Result = new RedirectResult(String.Concat(customErrorPage, "?action=", this.Action));
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;            
        }

        #endregion

        public string GetCustomError(string statusCode)
        {
            CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;

            if (customErrorsSection != null)
            {
                CustomError customErrorPage = customErrorsSection.Errors[statusCode];

                if (customErrorPage != null)
                    return customErrorPage.Redirect;
            }
            return null;
        }        
    }
}

What that code does is throw an 403 Exception if the user rights are not enough, then we implement the IExceptionFilter, so we can handle the error on our own way with the OnException method. Notice we are reading the customErrors section looking for the page that is set for the 403 code and redirecting the user to that page.

With that AuthorizationAttribute you can decorate any class or method that you want to be checked when a user access it, like so:

[AuthorizationAttribute]
[HandleError]
public class HomeController : Controller

Let’s create our page inside the Views folder (again, it can be the Shared or the Errors folder) to tell the user about the error:

AccessDenied.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Access Denied
</asp:Content>

<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Sorry, you do not have access to the action <%: ViewData["action"] %>.
    </h2>    
</asp:Content>

Add one more action method to our ErrorController:

public ActionResult AccessDenied(string action)
{
	ViewData["action"] = action;

	return View();
}

In this example, I’m passing in a parameter called “action” to the AccessDenied method, but it could be anything you want and can contain any information you want.

And finally, completing our Web.Config, we now add the treatment for the 403 error code:

<customErrors mode="On" defaultRedirect="Error">
  <error statusCode="404" redirect="Error/NotFound"/>
  <error statusCode="403" redirect="Error/AccessDenied"/>
</customErrors>

Here is how our ErrorController end up like:

namespace ErrorHandling.Controllers
{
    public class ErrorController : Controller
    {
        public ActionResult Index()
        {
            return View("Error");
        }

        public ActionResult NotFound(string aspxerrorpath)
        {
            ViewData["error_path"] = aspxerrorpath;

            return View();
        }

        public ActionResult AccessDenied(string action)
        {
            ViewData["action"] = action;

            return View();
        }
    }
}

With this structure the errors are very organized and all the things related to it are together.

Follow

Get every new post delivered to your Inbox.