2015-04-27 4 views
0
public class UsernameBinder: System.Web.Http.ModelBinding.IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     var key = bindingContext.ModelName; 
     var val = bindingContext.ValueProvider.GetValue(key); 

     if (val != null) 
     { 
      //????????????????????????????????????????? 
      //Get username property of user 
      //Set username property = User.Identity.Name 
     } 

     return false; 
    } 
} 

Я хочу создать привязку модели, которая автоматически связывает имя пользователя. Но я не мог получить собственность.asp.net mvc web api change parameter model binding

И я буду использовать его как это:

public SendMessage CreateMessage([ModelBinder(typeof(UsernameBinder))]Message message) 
{ 
} 

Как я могу получить свойство модели с Web API?

ответ

0

Я бы предложил прочитать http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api, что должно помочь вам привязать модель вашего метода действий к вашему User. Теперь, чтобы получить пользователь в WebAPI использует slighty другую convetion (для WebAPI НЕ WebAPI 2)

Такие, как

var username = ((ApiController)context.ControllerContext.Controller).User.Identity.Name;

0

Я не знаю, действительно ли я понял ваш вопрос, но я решил проблему как это выстрелил назад.

Задача: как получить currentUserId в действиях контроллера WebAPI?

// ex: update method 
public IHttpActionResult Put(int id, [FromBody] MyModel model, Guid userId) 

Решение:

Объявите связывания и атрибут:

public class CurrentUserIDParameterBinding : HttpParameterBinding 
{ 
    public CurrentUserIDParameterBinding(HttpParameterDescriptor parameter) 
     : base(parameter) 
    { 
    } 

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, 
    HttpActionContext actionContext, CancellationToken cancellationToken) 
    { 
     Guid userId = /* my userid based on provider */; 
     actionContext.ActionArguments[Descriptor.ParameterName] = userId; 
     return Task.FromResult<object>(null); 
    } 
} 

public class CurrentUserIDAttribute : ParameterBindingAttribute 
{ 
    public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter) 
    { 
     return new CurrentUserIDParameterBinding(parameter); 
    } 
} 

и использовать его как это:

public IHttpActionResult Put(int id, [FromBody] MyModel model, [CurrentUserID] Guid userId) 
0

может быть, вы хотите добавить связывание пользовательский параметр править?

так:

config.ParameterBindingRules.Insert(0, GetCustomParameterBinding); 

см пример How to pass ObjectId from MongoDB in MVC.net