0

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

1 Answer 1

1

@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...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.