Model-bind interface property with Web API

前端 未结 2 1899
醉话见心
醉话见心 2021-01-07 22:34

I have a command looking like:

public interface ICommand {
    // Just a marker interface
}

public interface IUserAware {
    Guid UserId { get; set; }
}

p         


        
2条回答
  •  温柔的废话
    2021-01-07 23:16

    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.

提交回复
热议问题