如何在MVC 6中编码多态模型Binder和Provider

时间:2016-11-08 17:20:02

标签: asp.net-mvc polymorphism modelbinder

此问题之前曾在SOC和其他地方的MVC3上下文中提出过,并且有关于它与ASP.NET Core RC1和RC2相关的一些问题,但不过一个例子实际上说明了如何以正确的方式做到这一点在MVC 6中。

有以下课程

 public abstract class BankAccountTransactionModel {

    public long Id { get; set; }
    public DateTime Date { get; set; }
    public decimal Amount { get; set; }
    public readonly string ModelType;
    public BankAccountTransactionModel(string modelType) {
        this.ModelType = modelType;
    }
 }

 public class BankAccountTransactionModel1 : BankAccountTransactionModel{

    public bool IsPending { get; set; }

    public BankAccountTransactionModel1():
            base(nameof(BankAccountTransactionModel1)) {}
 }    

 public class BankAccountTransactionModel2 : BankAccountTransactionModel{

    public bool IsPending { get; set; }

    public BankAccountTransactionModel2():
            base(nameof(BankAccountTransactionModel2)) {}
 }

在我的控制器中,我有类似的东西

[Route(".../api/[controller]")]  
public class BankAccountTransactionsController : ApiBaseController 
{

 [HttpPost]
 public IActionResult Post(BankAccountTransactionModel model) {

        try {
            if (model == null || !ModelState.IsValid) {
                // failed to bind the model
                return BadRequest(ModelState);
            }

            this.bankAccountTransactionRepository.SaveTransaction(model);

            return this.CreatedAtRoute(ROUTE_NAME_GET_ITEM, new { id = model.Id }, model);
        } catch (Exception e) {

            this.logger.LogError(LoggingEvents.POST_ITEM, e, string.Empty, null);
            return StatusCode(500);
        }
    }

}        

我的客户可以发布BankAccountTransactionModel1或BankAccountTransactionModel2,我想使用自定义模型绑定器来根据在抽象基类BankAccountTransactionModel上定义的属性ModelType中的值来确定要绑定的具体模型。

因此我做了以下

1)编写了一个简单的Model Binder Provider,它检查类型是否为BankAccountTransactionModel。如果是这种情况,则返回BankAccountTransactionModelBinder的实例。

public class BankAccountTransactionModelBinderProvider : IModelBinderProvider {

    public IModelBinder GetBinder(ModelBinderProviderContext context) {

        if (context == null) throw new ArgumentNullException(nameof(context));

        if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType) {     

            var type1 = context.Metadata.ModelType;
            var type2 = typeof(BankAccountTransactionModel);

            // some other code here?

            // tried this but not sure what to do with it!
            foreach (var property in context.Metadata.Properties) {
                propertyBinders.Add(property, context.CreateBinder(property));
            }

            if (type1 == type2) {
                return new BankAccountTransactionModelBinder(propertyBinders);
            }
        }

        return null;
    }
}

2)编写了BankAccountTransactionModel

 public class BankAccountTransactionModelBinder : IModelBinder {


 private readonly IDictionary<ModelMetadata, IModelBinder> _propertyBinders;

 public BankAccountTransactionModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders){
                this._propertyBinders = propertyBinders;
                  }
 public Task BindModelAsync(ModelBindingContext bindingContext) {

        if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext));            

        // I would like to be able to read the value of the property
        // ModelType like this or in some way...
        // This does not work and typeValue is...
        var typeValue = bindingContext.ValueProvider.GetValue("ModelType");

        // then once I know whether it is a Model1 or Model2 I would like to
        // instantiate one and get the values from the body of the Http  
        // request into the properties of the instance  

        var model = Activator.CreateInstance(type);

        // read the body of the request in some way and set the 
        // properties of model                                                                                                           

        var key = some key? 
        var result = ModelBindingResult.Success(key, model);

        // Job done  
        return Task.FromResult(result);
    }

 }

3)最后,我在Startup.cs中注册了提供程序

public void ConfigureServices(IServiceCollection services)
    {       
        services.AddMvc(options => {
            options.ModelBinderProviders.Insert(0, new BankAccountTransactionModelBinderProvider());
            options.Filters.Add(typeof (SetUserContextAttribute));
        });

整个事情看起来很好,实际上是调用了提供程序,模型构建器的情况也是如此。但是,我似乎无法在模型绑定器的BindModelAsync中编写逻辑编码。

正如代码中的注释已经说明的那样,我在模型绑定器中想要做的就是从http请求的主体读取,特别是在我的JSON中读取ModelType的值。然后在此基础上,我想实例化BankAccountTransactionModel1或BankAccountTransactionModel,最后通过读取它们在主体中的JSON来为这个实例的属性赋值。

我知道这只是对它应该如何完成的一个粗略的近似,但我非常感谢一些帮助,也许还有一些关于如何做或已经做过的例子。

我遇到过ModelBinder下面代码行的示例

var typeValue = bindingContext.ValueProvider.GetValue("ModelType");

应该读取该值。但是,它在我的模型绑定器中不起作用,而typeValue总是如下所示

typeValue
{}
Culture: {}
FirstValue: null
Length: 0
Values: {}
Results View: Expanding the Results View will enumerate the IEnumerable

我也注意到了

bindingContext.ValueProvider
Count = 2
[0]: {Microsoft.AspNetCore.Mvc.ModelBinding.RouteValueProvider}
[1]: {Microsoft.AspNetCore.Mvc.ModelBinding.QueryStringValueProvider}

这可能意味着因为它是我没有机会从身体中读取任何东西。

我是否需要一个&#34;格式化程序&#34;在混合中以获得理想的结果?

类似的自定义模型绑定器的参考实现是否已存在于某处,以便我可以简单地使用它,或许可以使用一些简单的mod?

谢谢。

0 个答案:

没有答案