5

I need to make a complex type parameter optional in 'Web API controller action', so that my action filter for null values can ignore it by checking the argument's property IsOptional. I'm getting this error:

Optional parameter 'errorCode' is not supported by 'FormatterParameterBinding'.

I have a controller like this:

[Route("api/v1/Temp/{number}/{errorCode?}/{value?}")]
[HttpGet]
public IHttpActionResult Temp(int number, ErrorDetail errorCode = null, string value = null)
{
    return Ok("good");
}

and have actionFilter to check null values like this:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    var parameters = actionContext.ActionDescriptor.GetParameters();
    foreach (var param in parameters)
    {
        if (param.IsOptional)
            continue;

        object value = null;

        if (actionContext.ActionArguments.ContainsKey(param.ParameterName))
            value = actionContext.ActionArguments[param.ParameterName];

        if (value == null)
            throw new GasException((ulong)ErrorCodes.NullValue, ErrorCodes.NullValue.GetDescription());
    }
}

Is there any way to make complex-types optional parameter? How to ignore complex-type optional parameters in action-filter?

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
  • I have found a way around, by using custom attribute on my controller action, which takes all the optional parameters and then skip those optional parameters in NULL value filter. – Muhammad Saad Javed Jan 17 '17 at 15:28

1 Answers1

0

It doesn't seem like you can. If the client making the request does not provide a value for the complex type parameter then it will automatically be provided as null by ASP.NET Web API since they are reference types.

Hence, no need to explicitly set them with a default value of null:

public IHttpActionResult Temp(int number, ErrorDetail errorCode, string value)
{
    return Ok("good");
}

By removing the = null default values in the method signature above that error regarding "optional param not supported..." goes away.

Not sure the intent of your action filter since you're checking for nulls and throwing an exception. That implies those parameters are truly required not optional.

Ray
  • 187,153
  • 97
  • 222
  • 204