The answer is to define you own HttpParameterBinding
.
Here is the example I've made.
First I've created my CustomParameterBinding
public class CustomParameterBinding : HttpParameterBinding
{
public CustomParameterBinding( HttpParameterDescriptor p ) : base( p ) { }
public override System.Threading.Tasks.Task ExecuteBindingAsync( System.Web.Http.Metadata.ModelMetadataProvider metadataProvider, HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken )
{
// Do your custom logic here
var id = int.Parse( actionContext.Request.RequestUri.Segments.Last() );
// Set transformed value
SetValue( actionContext, string.Format( "This is formatted ID value:{0}", id ) );
var tsc = new TaskCompletionSource<object>();
tsc.SetResult(null );
return tsc.Task;
}
}
The next step is to create custom attribute to decorate parameter:
public class CustomParameterBindingAttribute : ParameterBindingAttribute
{
public override HttpParameterBinding GetBinding( HttpParameterDescriptor parameter )
{
return new CustomParameterBinding( parameter );
}
}
And finally now controller looks like:
public class ValuesController : ApiController
{
// GET api/values/5
[Route( "api/values/{id}" )]
public string Get([CustomParameterBinding] string id )
{
return id;
}
}
So now when I call http://localhost:xxxx/api/values/5
I get: "This is formatted ID value:5"