Model-bind interface property with Web API

前端 未结 2 1877
醉话见心
醉话见心 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:08
    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  { ... }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题