Alex
Alex

Reputation: 423

How to get parameter from URL in actionContext ASP.NET Web API 2

If I have a route like this:

api/account/{id}/devices

how do I get the id value from actionContext in an action filter?

When the route was api/account/{id} I used

actionContext.Request.RequestUri.Segments.Last()

Is there a reliable way to get any parameter from url string if I know the parameter name, but not where it resides in url?

(ActionContext.ActionArguments are null, btw).

Upvotes: 0

Views: 1461

Answers (1)

Alex
Alex

Reputation: 423

@orsvon nudged me in a somewhat right direction:
What is Routedata.Values[""]?
In web api there is no ViewBag, but the idea is correct.
For anyone stumbling here:
If you have some filter or attribute and you need to get some parameter, you can do it like this:

public class ContractConnectionFilter : System.Web.Http.AuthorizeAttribute
{
    private string ParameterName { get; set; }

    public ContractConnectionFilter(string parameterName)
    {
        ParameterName = parameterName;
    }
    
    private object GetParameter(HttpActionContext actionContext) 
    {
        try
        {
            return actionContext.RequestContext.RouteData.Values
                //So you could use different case for parameter in method and when searching
                .Where(kvp => kvp.Key.Equals(ParameterName, StringComparison.OrdinalIgnoreCase))
                .SingleOrDefault()
                //Don't forget the value, Values is a dictionary
                .Value;
        }
        catch
        {
            return null;
        }
    }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        object parameter = GetParameter(actionContext);
        ... do smth...
    }
}

and use it like this:

[HttpGet, Route("account/{id}/devices/{name}")]
[ContractConnectionFilter(parameterName: "ID")] //stringComparison.IgnereCase will help with that
//Or you can omit parameterName at all, since it's a required parameter
//[ContractConnectionFilter("ID")]
public HttpResponseMessage GetDevices(Guid id, string name) {
    ... your action...
}

Upvotes: 1

Related Questions