Using PostSharp with ASP.Net MVC

Tagged Under : , , , ,

I’ve been diving into some new .Net frameworks and libraries lately and thought I should share some of the cool stuff I’ve learned. I’m going to share what I’ve learned while using PostSharp with the new ASP.Net MVC framework.

I have already posted a few things about the new MVC framework so I won’t explain why Im excited for it. But, I havent talked about PostSharp so lets go over that really quick. First, you NEED to watch this video. It goes over exactly what I am using PostSharp for and shows off its power in just a few minutes. Next, you need to read up on what Aspect Oriented Programming means. The wiki article is pretty complex though. What you need to take away from it is how it helps programmers ’separate concerns’, modularize your code, easily apply ‘aspects/modules’ to various parts of your code and avoid maintenance problems. Another good link is http://www.postsharp.org/aop.net/.

Let’s talk about the sample project now.

I needed a nice, clean way to add extra behaviors to the MVC Controllers as well as the Action methods within them without copy pasting code. More specifically, I needed the ability to run code before and after each method call. Usually, to achieve this you would add extra methods calls with the Action method to run your code and make a decision based on the results… BUT I didn’t want that! So here’s a simple example of how to apply security to Action methods as well as logging each invocation of an action.

To create the sample project I first created a new MVC Web Project and added the references from PostSharp (PostSharp.Public and PostSharp.Laos). In this example I required the user to be authenticated before they can click and visit the About page in the sample MVC site. To do this I created a new class that inherits from PostSharp.Laos.OnMethodBoundryAspect and implemented the virtual methods available. I then added my new Attribute to the About action method in the HomeController. Now everytime the About action is called it will actually run my authentication code BEFORE running the About code and I can make a decision about whether to let the user continue or not. I can even inject a different return value for the method!

I know I was pretty vague on the actual coding details, but you can just look at the simple solution itself.

Download It Here!

kick it on DotNetKicks.com

 

Make a comment

You must be logged in to post a comment.