0

A lot of our Web API action patterns have the following pattern:

public IHttpActionResult GetDetails(Guid customerGuid)
{
    Customer customer = customerRetriever.FromGuid(customerGuid);

    if (customer == null)
        return NotFound();

    // Do Stuff....
}

I want to move all the customer lookup boiler plate out of the action method. I created an action filter attribute to do this, by looking at the value of the action argument and setting a request property:

KeyValuePair<String, Object> argument = actionContext.ActionArguments.Single(kvp => kvp.Key.Equals(ParameterName));
Guid customerGuid = (Guid)argument.Value;
// Do customer lookup, return 404 if needed
// Add customer to request properties

This works, but i still need to include the now redundant Guid in my action signature. If i remove this, my approach for finding the Guid value fails. Is there a way to bind a value from the URI, without having that value as an action parameter?

1
  • is the customer id the id if the user making the call? or is the user making a call to view a particular customer? If the former then that is what authentication and authorization action filters are for. Commented Mar 29, 2017 at 23:29

1 Answer 1

0

You have to pass customerGuid as queryString parameter like http://localhost:61374/api/values?customerGuid=D09584F2-0B81-4855-8F33-567F4EF8096C Then you can fetch query string value in action filter as:

  public class CustomFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var queryStringValues = actionContext.Request.GetQueryNameValuePairs();
        var customerGuid = queryStringValues.FirstOrDefault(x => x.Key == "customerGuid").Value;
        //Your logic
    }
}

Now there is no need to specify params in API method

public IHttpActionResult GetDetails()
{
  //Do stuff
}
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.