Get route pattern from IOwinContext

I am looking to get a route pattern from a query. I use OwinMiddleware and override the Invoke method accepting IOwinContext.

public override async Task Invoke(IOwinContext context) { ... } 

Given the request url: http://api.mycatservice.com/Cats/1234

I want to get " Cats / {CatId} "

I tried unsuccessfully to convert it using the following approaches:

 HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod(context.Request.Method), context.Request.Uri); HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName); 

For reference:

Here is a post on how to do this using HttpRequestMessage , which I successfully implemented for another project

+6
source share
1 answer

I had the same problem, it seems to work. A bit of magic, but so far so good:

 public class RouteTemplateMiddleware : OwinMiddleware { private const string HttpRouteDataKey = "MS_SubRoutes"; private readonly HttpRouteCollection _routes; public RouteTemplateMiddleware(OwinMiddleware next, HttpRouteCollection routes) : base(next) { _routes = routes; } public override async Task Invoke(IOwinContext context) { var routeData = _routes.GetRouteData(new HttpRequestMessage(new HttpMethod(context.Request.Method), context.Request.Uri)); var routeValues = routeData?.Values as System.Web.Http.Routing.HttpRouteValueDictionary; var route = routeValues?[HttpRouteDataKey] as System.Web.Http.Routing.IHttpRouteData[]; var routeTemplate = route?[0].Route.RouteTemplate; // ... do something the route template await Next.Invoke(context); } } 

Register the middleware as follows:

 public void Configuration(IAppBuilder app) { _httpConfiguration = new HttpConfiguration(); _httpConfiguration.MapHttpAttributeRoutes(); ... app.Use<RouteTemplateMiddleware>(_httpConfiguration.Routes); ... } 
+2
source

All Articles