I have a command looking like:
public interface ICommand {
// Just a marker interface
}
public interface IUserAware {
Guid UserId { get; set; }
}
p
public class CreateSomethingModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string key = bindingContext.ModelName;
ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
if (val != null)
{
string s = val.AttemptedValue as string;
if (s != null)
{
return new CreateSomething(){Title = s; UserId = new Guid(ControllerContext.HttpContext.Request.Headers["userId"]);}
}
}
return null;
}
}
and add attribute on the type declaration
[ModelBinder(typeof(CreateSomethingModelBinder))]
public class CreateSomething { ... }
Based on @Todd last comment, the answer to the question is:
Create a HttpParameterBinding
class:
public class UserAwareHttpParameterBinding : HttpParameterBinding
{
private readonly HttpParameterBinding _paramaterBinding;
private readonly HttpParameterDescriptor _httpParameterDescriptor;
public UserAwareHttpParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor)
{
_httpParameterDescriptor = descriptor;
_paramaterBinding = new FromBodyAttribute().GetBinding(descriptor);
}
public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
await _paramaterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
var baseModel = actionContext.ActionArguments[_httpParameterDescriptor.ParameterName] as IUserAware;
if (baseModel != null)
{
baseModel.UserId = new Guid("6ed85eb7-e55b-4049-a5de-d977003e020f"); // Or get it form the actionContext.RequestContext!
}
}
}
And wire it up in the HttpConfiguration
:
configuration.ParameterBindingRules.Insert(0, descriptor => typeof(IUserAware).IsAssignableFrom(descriptor.ParameterType) ? new UserAwareHttpParameterBinding(descriptor) : null);
If anyone know how this is done in .NET Core MVC - please edit this post or comment.