Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")].

like image 668
Dmytro Zhluktenko Avatar asked Dec 07 '25 03:12

Dmytro Zhluktenko


1 Answers

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 :)

like image 195
Farshan Avatar answered Dec 08 '25 23:12

Farshan