Is there a way to decouple controller method input names from ActionFilterAttribute actionArguments and RouteData.Values dictionaries?

Viewed 74

I am running into this issue often and I wonder if there is a better way to do this.

I have APIControllers methods that have inputs e.g

[ProductDetailsValidation]
[HttpPost]
[Route("{productId}/details")]
public HttpResponseMessage PostProductDetails(
    [FromUri] string productId, 
    [FromBody] ProductDetails productDetails) 
{
    //...
}

And I have an action filter like this:

public class ProductDetailsValidationAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        //coupled to productId variable name
        string productId = actionContext.ControllerContext
            .RouteData
            .Values["productId"].ToString(); 

        Dictionary<string,object> data = actionContext.ActionArguments;

        //coupled to productDetails variable name
        ProductDetails details = (ProductDetails)data["productDetails"]; 

        //...
    }
}

I wonder if there is a way to decouple the names so renaming can happen without breaking the ProductDetailsValidationAttribute.

If there is no other way I wonder if it is possible to write a unit test that will trigger the ProductDetailsValidationAttribute with a mocked call to the APIController end-point. Of course I could have an integration test but that is not the point of the question.

Any help is really appreciated!

Thanks, Michael

0 Answers
Related