Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Register routes using attributes on your controller actions for ASP.NET MVC

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 build
Octocat-spinner-32 lib
Octocat-spinner-32 src
Octocat-spinner-32 tools
Octocat-spinner-32 .gitignore
Octocat-spinner-32 README
Octocat-spinner-32 build_and_publish_nuget_package.sh
README
This dll takes some of the pain away from registering routes in ASP.NET MVC (including having to alter your routes when you rename a controller !)
It's on Nuget as "Mvc.Routing"

So instead of registering routes like this :

	routes.MapRoute(
	    "foobar route",
	    "foo/{someParam}/bar",
	    new { controller = "Foo", action = "Bar" }
	);

You can just call :

	Routing.Register(typeof(MvcApplication).Assembly);

And then tag your controllers : 

public class FooController : Controller 
{
	[Get("foo/{someParam}/bar")]
	public ActionResult Bar(string someParam) {
		// whatever
	}
}

There are attributes for Get, Post, Put, Patch and Delete
The attributes behave like the normal HttpGet, HttpPost (etc) attributes - ie if you tag an action as Get(), then you can't post to it

You can use them in conjunction with the normal Http* attributes, for example :

public class FooController : Controller 
{
	[Get("foo/new")]
	public ActionResult New() {
		// whatever
	}

	[HttpPost]
	public ActionResult Create(Bar bar) {
		// whatever
	}
}

If you don't use the HttpGet / HttpPost attributes for your actions, you can still register routes like so :

public class FooController : Controller 
{
	[Route("foo/{id}")]
	public ActionResult View(Guid id) {
		// whatever
	}

	[Route("foos")]
	public ActionResult List() {
		// whatever
	}	
}

Testing your routes is also pretty simple, below is an example using Mspec (Machine.Specifications) :

    [Subject(typeof(TestController), "Given a test controller has marked the Index method as Get")]
    public class when_registering_routes : register_route_context
    {
        Establish context = () =>
        {
            theExpectedRouteUrl = "all/routes/are/mine";
            theExpectedActionName = "Index";
            theExpectedControllerName = "Test";
        };

        Because of = () =>
        {
            Routing.Register(typeof(TestController).Assembly);
            theRoute =
                RouteTable.Routes.Select(x => x as Route).Where(x => x.Url == theExpectedRouteUrl).FirstOrDefault();
        };

        Behaves_like<route_should_be_registered> route_should_be_registered;
    }

    See the project specs here for more examples : https://github.com/benjaminkeeping/Mvc.Routing/tree/master/src/Mvc.Routing.Specs/registration
Something went wrong with that request. Please try again.