Dmytro Zhluktenko
Dmytro Zhluktenko

Reputation: 160

How to get URL template path in ASP.NET Core?

I'm working on ActionFilter and need to get URL template path like /api/v{version}/controllerName/actionName/{parameter}. However, the solution needs to be generic so it supports multiple URL patterns like api/v{version}/controllerName/actionName/{parameter}/otherActionName/{otherParameter}.

ASP.NET Core 2.2 latest stable. What I have is ActionExecutedContext which contains HttpContext as well. However, I am not sure about the content of this HttpContext since it contains some default values for the response.

    private PathString GetUrlTemplatePath(ActionExecutedContext context)
    {
        // TODO:
        return context.HttpContext.Request.Path;
    }

Actual result: /api/v1/Location/addresses/999999A1-458A-42D0-80AA-D08A3DAD8199.

Expected result: /api/v{version}/location/addresses/{externalId} where externalId is a name of parameter described by an attribute [HttpGet("addresses/{externalId}", Name = "GetAddress")].

Upvotes: 2

Views: 4620

Answers (2)

Farshan
Farshan

Reputation: 436

You can get the template path from your ActionExecutedContext from your ResourceFilter. if you need QueryString for your problem or there is ActionArguments in the context of type Dictionary<string, object>which contains all the parameters passed with the request.

//template
string template = context.ActionDescriptor.AttributeRouteInfo.Template;;

//arguments
IDictionary<string, object> arguments = context.ActionArguments;

//query string
string queryString= context.HttpContext.Request.QueryString.Value;

Hope this helps :)

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190945

You can get part of it from the context.ActionDescriptor.AttributeRouteInfo. I'm not 100% sure if that would be complete or just a partial piece of it.

Upvotes: 0

Related Questions