Created
May 11, 2014 22:57
-
-
Save pmhsfelix/4eee4a6b152942dc15e0 to your computer and use it in GitHub Desktop.
Parent-child routing with ASP.NET Web API. Too "hackish"?
This file contains hidden or 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
public class ParentChildController : ApiController | |
{ | |
public string Get(int pid, int cid) | |
{ | |
return string.Format("{0}:{1}",pid,cid); | |
} | |
} | |
class ParentChildRoutingTranslator : DelegatingHandler | |
{ | |
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
var routeData = request.GetRouteData(); | |
if(!routeData.Values.ContainsKey("controller")) | |
{ | |
object parent; | |
object child; | |
if (routeData.Values.TryGetValue("parent", out parent) | |
&& routeData.Values.TryGetValue("child", out child)) | |
{ | |
routeData.Values.Add("controller", parent.ToString() + child); | |
} | |
} | |
return base.SendAsync(request, cancellationToken); | |
} | |
} | |
class ParentChildRouting : IDemo | |
{ | |
public string Description { | |
get { return "Parent-child routing demo"; } | |
} | |
public Task Run() | |
{ | |
using (WebApp.Start("http://localhost:8080", app => | |
{ | |
var config = new HttpConfiguration(); | |
config.Routes.MapHttpRoute( | |
"ParentChild", | |
"{parent}/{pid}/{child}/{cid}", | |
new {cid = RouteParameter.Optional}, | |
new {}, | |
HttpClientFactory.CreatePipeline( | |
new HttpControllerDispatcher(config), | |
new []{ | |
new ParentChildRoutingTranslator() | |
} | |
)); | |
app.UseWebApi(config); | |
})) | |
{ | |
Console.WriteLine("Server is running"); | |
Console.ReadKey(); | |
} | |
return Task.FromResult<object>(null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment