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;
    }
}

I want to create a model binder that binds username of user automatically. But I cauld not get property.

And I will use it like this:

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

How can I get property of a model from Web API?

barteloma
  • 6,403
  • 14
  • 79
  • 173

3 Answers3

0

I would suggest reading http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api this should help you to bind the model of your action method to your User. Now to get the user in WebApi uses a slighty different convetion (for WebApi NOT WebApi 2)

Such as

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

Nico
  • 12,493
  • 5
  • 42
  • 62
0

I do not know if I really understood your question, but I solved a problem like this a shot time ago.

Problem: how to get the currentUserId in WebAPI controller actions?

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

Solution:

Declare a binding and attribute:

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);
    }
}

and use it like this:

public IHttpActionResult Put(int id, [FromBody] MyModel model, [CurrentUserID] Guid userId)
Filipe Borges
  • 2,712
  • 20
  • 32
0

may be you want to add custom parameter binding rule?

like this:

config.ParameterBindingRules.Insert(0, GetCustomParameterBinding);

see example How to pass ObjectId from MongoDB in MVC.net

razon
  • 3,882
  • 2
  • 33
  • 46