Model-bind interface property with Web API

前端 未结 2 1879
醉话见心
醉话见心 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  { ... }
    

提交回复
热议问题