Tuesday, April 9, 2013

Returning an HTTP 403 Forbidden error with ASP.NET MVC

Sometimes it can be useful, in case of error, to return a custom error message to the user along with the HTTP 403 (Forbidden) status code.
This usually indicates that the access to the requested resource is denied for some reason and the server cannot proceed. Unlike the 401 Unauthorized status, which means an unauthorized access, correct credentials will not allow you to view the page.

To handle this scenario in ASP.NET MVC we can create a custom helper which must meet the following conditions:
  • It must be easy and straightforward to use
  • It must return a 403 status code along with the Forbidden status
  • It must not perform a redirect but the page URL should stay the same
  • It must display a custom view to the user
My HttpForbiddenResult class inherits from the HttpStatusCodeResult class which already exists in ASP.NET MVC. In this way, the framework will automatically set the status code and the description. The complete code of the class is the following:

public class HttpForbiddenResult : HttpStatusCodeResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        base.ExecuteResult(context);

        // creates the ViewResult adding ViewData and TempData parameters
        ViewResult result = new ViewResult
        {
            ViewName = "AccessDenied",
            ViewData = context.Controller.ViewData,
            TempData = context.Controller.TempData
        };

        result.ExecuteResult(context);
    }

    // calls the base constructor with 403 status code
    public HttpForbiddenResult()
        : base(HttpStatusCode.Forbidden, "Forbidden")
    {
    }
}

I have also created a view called AccessDenied within the Shared folder, which contains a custom message for the users who will view the page:

@{
    ViewBag.Title = "Access Denied";
}

<h2>Access Denied</h2>

<p>Sorry, the access to this page is denied.</p>

In order to use the helper you need just the following lines of code:

public class HomeController : Controller
{
    public ActionResult DoSomething(string taskName)
    {
        // access denied if taskName is empty
        if (string.IsNullOrEmpty(taskName))
        return new HttpForbiddenResult();

        return View();
    }
}

If you visit the URL for the previous controller without the taskName parameter, you will see the following result:


Of course, with little modifications you can create a custom helper for all the HTTP error codes!

Restituire un errore HTTP 403 Forbidden con ASP.NET MVC

Alle volte può essere utile, in caso di errore, restituire all'utente un messaggio personalizzato insieme al codice HTTP 403 (Forbidden).
Questo indica solitamente che l'accesso alla risorsa richiesta è vietato per qualche ragione e il server non può procedere altrimenti. Diversamente dallo stato 401 Unauthorized, che indica un accesso non autorizzato, le credenziali non servono e non permetterebbero comunque di visualizzare la pagina.

Per gestire questa situazione in ASP.NET MVC possiamo creare un helper personalizzato che deve soddisfare le seguenti condizioni:
  • Deve essere facile e immediato da utilizzare
  • Deve restituire al browser il codice di errore 403 insieme allo stato Forbidden
  • Non deve effettuare un redirect ma la pagina deve rimanere la stessa
  • Deve mostrare all'utente una view personalizzata
Ho creato la classe HttpForbiddenResult ereditando dalla classe HttpStatusCodeResult già esistente in ASP.NET MVC. In questo modo il framework si occuperà automaticamente di impostare il codice di errore e la descrizione. Il codice completo della classe è il seguente:

public class HttpForbiddenResult : HttpStatusCodeResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        base.ExecuteResult(context);

        // crea il ViewResult impostando anche i parametri ViewData e TempData
        ViewResult result = new ViewResult
        {
            ViewName = "AccessDenied",
            ViewData = context.Controller.ViewData,
            TempData = context.Controller.TempData
        };

        result.ExecuteResult(context);
    }

    // richiama il costruttore base con il codice 403
    public HttpForbiddenResult()
        : base(HttpStatusCode.Forbidden, "Forbidden")
    {
    }
}

Ho creato quindi una view chiamata AccessDenied all'interno della cartella Shared, contenente un messaggio per gli utenti che visualizzeranno la pagina di errore:

@{
    ViewBag.Title = "Access Denied";
}

<h2>Access Denied</h2>

<p>Sorry, the access to this page is denied.</p>

Per utilizzare l'helper appena creato saranno sufficienti le seguenti linee di codice:

public class HomeController : Controller
{
    public ActionResult DoSomething(string taskName)
    {
        // accesso negato quando il parametro taskName è vuoto
        if (string.IsNullOrEmpty(taskName))
        return new HttpForbiddenResult();

        return View();
    }
}

Andando quindi con il browser alla URL del controller precedente senza il parametro taskName il risultato sarà questo:


Chiaramente con le opportune modifiche è possibile realizzare un helper per tutti i codici di errore HTTP che ci interessano!

Tuesday, April 2, 2013

Debugging into ASP.NET MVC 4 source code

Introduction


As you may know, ASP.NET MVC 4 it's an open source project and the code is freely available on CodePlex.
You can download and explore it to see how they have implemented some of the classes we are interested in or just to understand a little more about the entire framework.
In my case, for example, it has been very useful to see how the HandleError attribute is automatically serving the Error view in case of exception.
Sometimes it could be more useful to directly enter into the source code at runtime and see which operations are performed, watch or change the values of the variables and jump from one part of the code to another.
Today I will show then how to debug a web application into the source code of ASP.NET MVC 4 without the need to download and compile the whole project from CodePlex.
In order to do this we will use the SymbolSource server, which publicly provides the PDB symbols required to perform remote debugging in Visual Studio.
The PDB files are automatically created when the source code is compiled in debug mode and they contain information used to debug the code at runtime. These files are not usually included when we download the DLL files for an external library.
To obtain the PDB files of an external library (ASP.NET MVC 4 in this case) there are two ways:

  • Download and compile the source code of the library (if available)
  • Use SymbolSource and remote debugging

If you want to learn more about the PDB files you can read this this post.

Visual Studio Configuration


First you need to configure Visual Studio so that it can connect to the SymbolSource server and download the PDB files.
To do that, follow these steps:

  • Go to Tools -> Options -> Debugger -> General
  • Uncheck the option Enable Just My Code (Managed Only)
  • Uncheck the option Enable. NET Framework source stepping (this is optional)
  • Check the option Enable source server support
  • Uncheck the option Require source files to exactly match the original version

The options screen should look like this:


Now you must set the servers from which to download the PDB files:

  • Go to Tools -> Options -> Debugger -> Symbols
  • You should see only one item: Microsoft Symbol Servers
  • Click the exlamation mark icon to the right and add the following addresses:
    • http://referencesource.microsoft.com/symbols
    • http://srv.symbolsource.org/pdb/Public
    • http://srv.symbolsource.org/pdb/MyGet
    • http://msdl.microsoft.com/download/symbols
  • If needed, select a folder for the cache: in my case it is set to C:\Users\Luca\AppData\Local\Temp\SymbolCache

The screen should look like this:



Finally you need to specify the DLL files you want to load, otherwise Visual Studio will load all the modules and debugging becomes very slow.
In this case we are only interested in ASP.NET MVC, so click on Only specified modules, then click on Specify modules and insert System.Web.Mvc.dll:


Press OK and exit from the options screens.
Now we're almost done and we just need to open or create a new ASP.NET MVC 4 application, place a breakpoint and start debugging with Debug -> Start Debugging.
If everything went well, in the Call Stack window you should see the ASP.NET MVC modules in black:


Now when you press Debug -> Step Into on an ASP.NET MVC statement you will enter directly into the source code of the framework, with a lot of comments too!


Help me! It doesn't work!


If the modules in the Call Stack window are still appearing in gray and you can't enter into the source code of the framework, you can try the following solutions:

Make sure you followed all the steps and you have checked all the required options. In particular, make sure that you have removed the check from Require source files to exactly match the original version and entered all the SymbolSource addresses in the right order.

Try uninstalling and reinstalling the ASP.NET MVC 4 NuGet package (you don't have to reinstall the program, just the package!).

If you still cannot run the debugger, there is a final solution that worked fine for me.

It appears that in some cases the DLL files in the GAC (Global Assembly Cache) prevent Visual Studio from loading the PDB files from the remote server.

Reinstalling ASP.NET MVC did not help in my case (I just lost a lot of time) but I solved this problem in the following way:

  • Go to C:\Windows\Microsoft.NET\assembly\GAC_MSIL
  • Find the folder called System.Web.Mvc
  • Rename it, for example _System.Web.Mvc

In this way, the DLL files for ASP.NET MVC will not be searched in the GAC allowing you to connect to the SymbolSource server and download the PDB files.


Welcome to my blog

Welcome to my blog dedicated to two of my favorite passions: programming and cooking.

It's a rather strange combination and it will not be easy to write quality content for both categories.

The recipes won't be complex but fairly quick and easy to make! The other posts will span from .NET programming to Ruby on Rails, from Windows to Xubuntu.

About me, I'm a web programmer with a big passion for computing. I am currently working in a company as a .NET developer but in my free time I like to explore new programming languages ​​and technologies.

Let's begin this little adventure!


Hello English World!

Poichè il mondo dell'informatica è prevalentemente orientato alla lingua inglese, ho deciso di tradurre i post inseriti fino a oggi, aggiungendo d'ora in avanti la traduzione per ogni articolo che inserirò.

Happy reading :)