Skip to content

Instantly share code, notes, and snippets.

@kamsar
Created May 3, 2014 02:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamsar/41b36cbf412b81c1d75a to your computer and use it in GitHub Desktop.
Save kamsar/41b36cbf412b81c1d75a to your computer and use it in GitHub Desktop.
Web API attribute routing sample controller
using System.Collections.Generic;
using System.Web.Http;
namespace Foo.Web.Sites.ExampleSite.Shared.Data
{
// for more on Attribute Routing (used in this sample to create routes), see http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
// the RoutePrefix is the base path to the API controller
[RoutePrefix("ExampleSite/api/Sample")]
// this defines how to perform default route lookups on methods (e.g. this routes the action to a method of the same name like asp.net MVC, and sets Get() to the default action)
[Route("{action=Get}")]
public class SampleController : ApiController
{
// GET ExampleSite/api/Sample
public IEnumerable<object> Get()
{
return new[]
{
new { foo="foo", bar="bar"},
new { foo="baz", bar="bonk" }
};
}
// GET ExampleSite/api/Sample/Foos
public string Foos()
{
return "hello world";
}
// GET ExampleSite/api/Sample/5/lolcats
// This overrides the default route lookup scheme - you can pass params to the route that form URL segments
[Route("{id:int}/{boink}")]
public object Get(int id, string boink)
{
return new
{
id, boink
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment