Understanding Routing

One of the important feature of ASP.NET MVC is Routing. The Routing infrastructure helps us to map the incoming requests to controllers and actions. The routing module ships with a separate assembly System.Web.Routing and that helps us to use the routing infrastructure outside ASP.NET MVC applications, like in Webforms.

In this article we are going to see about the important details of routing infrastructure. First we start from basics and slowly move to the advanced concepts and at-last we see how we can simplify creating routes by using our own extension methods. For people who are already familiar with the basic things they can jump to the last section where we discuss about creating cool extension methods and that's fun.

Continue Reading

Creating non-variable querystrings using action link helpers

This post is more kind of tip. The action link html helpers really simplifies our job in generating hyperlinks. These html helpers are integrated with the routing infrastructure and that helps to generate links very smartly. There are lot of overloaded versions available but most of them takes the route values as an anonymous object.

Suppose we need to generate an URL like below,

The querystring names contains a "." operator and when you use an anonymous object to pass these values as new { = 12.12, pos.lon = 23.5 } you will run into an exception. How we generate urls like them using built-in action-link helpers is the rest of this post.

Continue Reading

CSRF and AntiForgeryToken

Cross Site Request Forgery also known as CSRF (XSRF) is a widely exploited website vulnerability. In a CSRF attack, a malicious site instructs a victim's browser to send a request to an honest site, as if request were part of the victim's interaction with the honest site, leveraging the victim's network connectivity and the browser's state, such as cookies, to disrupt the integrity of the victim's session with the honest site. One of the popular technique to prevent CSRF attack is by using security tokens (from here).

ASP.NET MVC suports prevention against CSRF through the AntiForgeryToken html helper and ValidateAntiForgeryToken filter. The AntiForgeryToken is supported only for the POST requests and not for GET and this makes sense because the GET operation has to used only for safe operations (as per HTTP spec.).

In some applications we need all the POST operations should be validated for the anti-forgery token and in those cases instead of decorating all the POST actions in the application with the ValidateAntiForgeryTokenAttribute we can create a custom authorization filter and apply it globally, that's what we are going to see in this article. We will also see how to create a html helper that renders form along with the hidden field that contains security token.

Continue Reading

How to create a custom session value provider

Value Providers are the components that feeds data to model binders. The framework contains a bunch of built-in value providers like FormValueProvider, RouteDataValueProvider, QueryStringValueProvider and HttpFileCollectionValueProvider that fetches data from Request.Form, Request.QueryString, Request.Files and RouteData.Values. These Value Providers are called in the order they are registered and so the one that registered earlier gets the first chance. We can easily restrict the model to bind with data from a particular Value Provider.

The interesting thing is we can even create own custom Value Provider to feed data to models. In this article we see how to create a value provider that feed data from session.

Continue Reading

Preventing access to folders using RouteExistingFiles property

When a user request for a static resource like an image, video etc. that is located in a particular folder the ASP.NET happily serves that resource to the user unless we have set some restrictions. Sometimes we need to protect these folders from delivering these resources to users other than the owner. In simple cases we can prevent this through web.config settings but in complex cases like it would be nice if we could control the accessibility through an action/filter and for that we have to direct those requests through MVC pipeline and there comes the RouteExistingFiles property. By setting this property to true we can say MVC to handle those requests instead of giving that responsibility to IIS.

In this article we will see how we can utilize the RouteExistingFiles property with an authorization filter to prevent users from accessing unauthorized resources.

Continue Reading

Customizing property binding through attributes

I don't need to say much about model binding, most of us aware of that. The built-in DefaultModelBinder takes away most of the burden from our shoulders and it's ideal in most of the cases. But in some cases the DefaultModelBinder is not enough for binding a particular model or a property and in those cases normally we go for creating a custom model binder either by creating a brand new one by implementing IModelBinder or by extending the DefaultModelBinder.

The created custom model binder can be registered to a model by two ways either by adding into the Binders collection in Global.asax.cs or through the ModelBinderAttribute. The created custom model binder can be linked to a class but not to a property.

In this article we will see how we can attach custom binding behaviors to a property through attributes.

Continue Reading

UpdateModel/TryUpdateModel gotchas with models created through reflection

The Model Binding feature takes away most of the burden from developers by taking the responsibility of model instantiation from the information available in the request. Sometimes we meet cases where we need to trigger the model binding process explicitly inside a controller. MVC provides two methods for rescue: UpdateModel and TryUpdateModel.

Both these methods perform the same operation, that is they update the model from the value providers. The difference between them is the UpdateModel throws exception if the model state is not valid while TryUpdateModel returns a boolean as false. Both these methods are generic and we don't need to explicitly specify the generic parameter.

Both the methods take overloads that accepts an IValueProvider. When you don't pass a particular value provider the controller uses all the available value providers to fill the instantiated model.

There is a peculiar problem with these two methods when we try to bind a model that is instantiated through reflection. In this article we are going to see about the issue and how we can overcome that.

Continue Reading

Model binding posted file to byte array

The improvements made in model binding from ASP.NET MVC 2 helps to easily map the uploaded files to models. The HttpPostedFileBaseModelBinder is the one that maps the file(s) available in the Request.Files to single or collection of HttpPostedFileBase instances. Whenever you have HttpPostedFileBase as a parameter in an action method or as a property in the model the HttpPostedFileBaseModelBinder comes to play and does the magic.

But sometimes we need little more convenience for ex. when an uploaded file needs to be persisted in database, we would love to have the uploaded file automatically converted into a byte array and available right in the action.

In this article we are going to see how we can achieve that by extending the built-in ByteArrayModelBinder.

Continue Reading

Customizing Authorize attribute

The Authorize attribute available in MVC framework helps to restrict users from accessing secured controllers and actions. When a user who is not authenticated or authorized tries to access the controller or action that is decorated with Authorize attribute generates a 401 response and if the site has forms authentication enabled then the user will be redirected to the login page. The problem with this behavior is the authenticated user (but not authorized) also get redirected to the login page, mostly developers like to show an access denied page in those case.

This article is mostly a kind of tip that describes how we can achieve that by extending the built-in Authorize attribute.

Continue Reading

Creating a custom Ajax Helper

Unobtrusive Ajax is an approach in which the ajax behaviors are separated out from the HTML elements. The ASP.NET MVC framework provides supports for ajax using the AjaxHelper and AjaxHelperExtensions classes. The MVC supports unobtrusive ajax with the help of jquery

In this article we will see how to create an custom ajax helper in ASP.NET MVC.

Continue Reading