Last active
August 29, 2015 14:03
-
-
Save miso-soup/f0c64c8dfde9e672a80b to your computer and use it in GitHub Desktop.
ASP.NET Web API 2.2 の IDirectRouteProvider を使用して、すべてのアクションに "{controller}/{action}" という UrlTemplate を付与した状態にしてみた。(が、全く実用的ではないし、converntion-base で一発でできる。)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Web.Http; | |
namespace WebApplication86.Controllers | |
{ | |
public class ValuesController : ApiController | |
{ | |
// GET value/get | |
public IEnumerable<string> Get() | |
// GET values/get?id={id} | |
public string Get(int id){ } | |
// POST values/post | |
public void Post([FromBody]string value){ } | |
// PUT values/put?id={id} | |
public void Put(int id, [FromBody]string value){ } | |
// DELETE values/delete?id={id} | |
public void Delete(int id){ } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Web.Http; | |
using System.Web.Http.Controllers; | |
using System.Web.Http.Routing; | |
namespace WebApplication86 | |
{ | |
public static class WebApiConfig | |
{ | |
public static void Register(HttpConfiguration config) | |
{ | |
config.MapHttpAttributeRoutes(new MyDirectRouteProvider()); | |
} | |
} | |
public class MyDirectRouteProvider : IDirectRouteProvider | |
{ | |
public IReadOnlyList<RouteEntry> GetDirectRoutes( | |
System.Web.Http.Controllers.HttpControllerDescriptor controllerDescriptor, | |
IReadOnlyList<System.Web.Http.Controllers.HttpActionDescriptor> actionDescriptors, | |
IInlineConstraintResolver constraintResolver) | |
{ | |
// {controller}/{action} の direct route を作成する | |
var entries = new List<RouteEntry>(); | |
string controllerName = controllerDescriptor.ControllerName; | |
foreach(HttpActionDescriptor action in actionDescriptors) | |
{ | |
string actionName = action.ActionName; | |
string template = String.Format("{0}/{1}", controllerName, actionName); | |
var context = new DirectRouteFactoryContext( | |
prefix: "", | |
actions: new HttpActionDescriptor[] { action }, | |
inlineConstraintResolver: constraintResolver, | |
targetIsAction: true); | |
IDirectRouteBuilder builder = context.CreateBuilder(template); | |
var routeEntry = builder.Build(); | |
entries.Add(routeEntry); | |
} | |
return entries; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment