Jean
Jean

Reputation: 5101

Find route variables from attribute

I would like to autofill ViewContext with 1 parameter of routes, however sometimes it is in query, sometimes it is in Url.

When in query, it is easy to get the parameter using req.Query.TryGetValue(key, out StringValues val). However I am looking for a way to capture the route parameter when it is like this:

[PrefillViewContext("postId")]
[HttpGet("/Post/{postId}")]
public IActionResult DisplayPost(Guid postId) {}

Is there a way to get this postId value outside of the method body, and use it in the attribute just above? (or in an attribute at class level)

Upvotes: 0

Views: 172

Answers (1)

Ryan
Ryan

Reputation: 20106

You could get action parameters using ActionExecutingContext by inheriting ActionFilterAttribute.You could get all RouteData from the context.

public class PrefillViewContextAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var postId = context.ActionArguments["PostId"];
    }

}

Upvotes: 1

Related Questions