web api get route template from inside handler

后端 未结 4 1526
春和景丽
春和景丽 2021-01-12 06:05

I searched a lot before putting the questions here but the more I search the more confused I get.

So I have created an handler and I am trying to get the route like

4条回答
  •  天命终不由人
    2021-01-12 06:28

    The answer from Marco (shown below) is correct so long as there isn't more than one route defined with the same HttpMethod. The .First() will grab the 1st route defined in that specific ApiController, but this doesn't ensure it grabs the correct one. If you use the ControllerContext to get the Route, you can be sure you've got the exact endpoint you want.

    Marco's:

    var routeTemplate = ((IHttpRouteData[])request.GetConfiguration()
                         .Routes.GetRouteData(request).Values["MS_SubRoutes"])
                         .First().Route.RouteTemplate;
    

    The code:

    ((IHttpRouteData[])request.GetConfiguration()
                         .Routes.GetRouteData(request).Values["MS_SubRoutes"])
    

    actually returns a collection of IHttpRouteData, and it contains a record for each endpoint which has the same HttpMethod (Post, Get, etc)... The .First() doesn't guarantee you get the one you want.

    Guaranteed To Grab Correct Endpoint's RouteTemplate:

    public static string GetRouteTemplate(this HttpActionContext actionContext)
    {
        return actionContext.ControllerContext.RouteData.Route.RouteTemplate;
    } 
    

    I used an extension method so to call this you'd do:

    var routeTemplate = actionContext.GetRouteTemplate();
    

    This will assure that you get the specific RouteTemplate from the endpoint making the call.

提交回复
热议问题