1. <small id='4moa4'></small><noframes id='4moa4'>

      1. <legend id='4moa4'><style id='4moa4'><dir id='4moa4'><q id='4moa4'></q></dir></style></legend>
        <tfoot id='4moa4'></tfoot>
          <bdo id='4moa4'></bdo><ul id='4moa4'></ul>
        <i id='4moa4'><tr id='4moa4'><dt id='4moa4'><q id='4moa4'><span id='4moa4'><b id='4moa4'><form id='4moa4'><ins id='4moa4'></ins><ul id='4moa4'></ul><sub id='4moa4'></sub></form><legend id='4moa4'></legend><bdo id='4moa4'><pre id='4moa4'><center id='4moa4'></center></pre></bdo></b><th id='4moa4'></th></span></q></dt></tr></i><div id='4moa4'><tfoot id='4moa4'></tfoot><dl id='4moa4'><fieldset id='4moa4'></fieldset></dl></div>

        asp net core rc2.抽象类模型绑定

        Asp net core rc2. Abstract class model binding(asp net core rc2.抽象类模型绑定)
      2. <tfoot id='Wns86'></tfoot>
        <i id='Wns86'><tr id='Wns86'><dt id='Wns86'><q id='Wns86'><span id='Wns86'><b id='Wns86'><form id='Wns86'><ins id='Wns86'></ins><ul id='Wns86'></ul><sub id='Wns86'></sub></form><legend id='Wns86'></legend><bdo id='Wns86'><pre id='Wns86'><center id='Wns86'></center></pre></bdo></b><th id='Wns86'></th></span></q></dt></tr></i><div id='Wns86'><tfoot id='Wns86'></tfoot><dl id='Wns86'><fieldset id='Wns86'></fieldset></dl></div>

        <legend id='Wns86'><style id='Wns86'><dir id='Wns86'><q id='Wns86'></q></dir></style></legend>
            • <bdo id='Wns86'></bdo><ul id='Wns86'></ul>

            • <small id='Wns86'></small><noframes id='Wns86'>

                  <tbody id='Wns86'></tbody>

                  本文介绍了asp net core rc2.抽象类模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  在 RC1 中,我使用以下代码进行抽象类或接口绑定:

                  In the RC1 I use the following code for abstract classes or interfaces binding:

                  public class MessageModelBinder : IModelBinder {
                  
                      public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) {
                          if(bindingContext.ModelType == typeof(ICommand)) {
                              var msgTypeResult = bindingContext.ValueProvider.GetValue("messageType");
                              if(msgTypeResult == ValueProviderResult.None) {
                                  return ModelBindingResult.FailedAsync(bindingContext.ModelName);
                              }
                              var type = Assembly.GetAssembly(typeof(MessageModelBinder )).GetTypes().SingleOrDefault(t => t.FullName == msgTypeResult.FirstValue);
                              if(type == null) {
                                  return ModelBindingResult.FailedAsync(bindingContext.ModelName);
                              }
                              var metadataProvider = (IModelMetadataProvider)bindingContext.OperationBindingContext.HttpContext.RequestServices.GetService(typeof(IModelMetadataProvider));
                              bindingContext.ModelMetadata = metadataProvider.GetMetadataForType(type);
                          }
                          return ModelBindingResult.NoResultAsync;
                      }
                  }
                  

                  此绑定器仅从查询字符串中读取模型类型(messageType 参数)并覆盖元数据类型.其余的工作由标准绑定器执行,例如 BodyModelBinder.

                  This binder only reads model type (messageType parameter) from query string and overrides metadata type. And the rest of the work performed by standard binders such as BodyModelBinder.

                  在 Startup.cs 我只添加第一个活页夹:

                  In Startup.cs I just add first binder:

                  services.AddMvc().Services.Configure<MvcOptions>(options => {
                      options.ModelBinders.Insert(0, new MessageModelBinder());
                  });
                  

                  控制器:

                  [Route("api/[controller]")]
                  public class MessageController : Controller {
                      [HttpPost("{messageType}")]
                      public ActionResult Post(string messageType, [FromBody]ICommand message) {
                      } 
                  }
                  

                  如何在 RC2 中执行此操作?

                  How can I perform this in RC2?

                  据我了解,现在我必须使用 IModelBinderProvider.好的,我试过了.启动.cs:

                  As far as I understand, now I have to use IModelBinderProvider. OK, I tried. Startup.cs:

                  services.AddMvc().Services.Configure<MvcOptions>(options => {
                      options.ModelBinderProviders.Insert(0, new MessageModelBinderProvider());
                  });
                  

                  ModelBinderProvider:

                  ModelBinderProvider:

                  public class MessageModelBinderProvider : IModelBinderProvider {
                      public IModelBinder GetBinder(ModelBinderProviderContext context) {
                          if(context == null) {
                              throw new ArgumentNullException(nameof(context));
                          }
                          return context.Metadata.ModelType == typeof(ICommand) ? new MessageModelBinder() : null;
                      }
                  }
                  

                  模型绑定器:

                  public class MessageModelBinder : IModelBinder {
                      public Task BindModelAsync(ModelBindingContext bindingContext) {
                          if(bindingContext.ModelType == typeof(ICommand)) {
                              var msgTypeResult = bindingContext.ValueProvider.GetValue("messageType");
                              if(msgTypeResult == ValueProviderResult.None) {
                                  bindingContext.Result = ModelBindingResult.Failed(bindingContext.ModelName);
                                  return Task.FromResult(0);
                              }
                              var type = typeof(MessageModelBinder).GetTypeInfo().Assembly.GetTypes().SingleOrDefault(t => t.FullName == msgTypeResult.FirstValue);
                              if(type == null) {
                                  bindingContext.Result = ModelBindingResult.Failed(bindingContext.ModelName);
                                  return Task.FromResult(0);
                              }
                              var metadataProvider = (IModelMetadataProvider)bindingContext.OperationBindingContext.HttpContext.RequestServices.GetService(typeof(IModelMetadataProvider));
                              bindingContext.ModelMetadata = metadataProvider.GetMetadataForType(type);
                              bindingContext.Result = ModelBindingResult.Success(bindingContext.ModelName, Activator.CreateInstance(type));
                          }
                          return Task.FromResult(0);
                      }
                  }
                  

                  但我不能指定 NoResult.如果我没有指定 bindingContext.Result,我会在控制器中得到空模型.如果我指定 bindingContext.Result,我会得到空模型而不设置模型字段.

                  But I cannot specify NoResult. If I do not specify bindingContext.Result, I get null model in controller. If I specify bindingContext.Result, I get empty model without setting model fields.

                  推荐答案

                  我对自定义模型绑定和抽象类有类似的要求以及 dougbu 在 github AspNet/Mvc/issues/4703为我工作.我从 RC1 升级到 ASP.NET Core 1.0,需要根据他的建议修改我的自定义模型绑定器.我已经复制 &将他的代码粘贴在下面,以防 github 问题的链接中断.阅读 github 问题中的评论,了解有关在服务器上创建请求类型的对象的代码的安全注意事项.

                  I had a similar requirement with custom model binding and abstract classes and the suggestions posted by dougbu on github AspNet/Mvc/issues/4703 worked for me. I upgraded from RC1 to ASP.NET Core 1.0 and needed to modify my custom model binder with his recommendations. I've copy & pasted his code below in case the link to the github issue breaks. Read the comments in the github issue for security considerations around code that creates objects of a requested type on the server.

                  public class MessageModelBinderProvider : IModelBinderProvider 
                  {
                      public IModelBinder GetBinder(ModelBinderProviderContext context)
                      {
                          if (context == null)
                          {
                              throw new ArgumentNullException(nameof(context));
                          }
                  
                          if (context.Metadata.ModelType != typeof(ICommand))
                          {
                              return null;
                          }
                  
                          var binders = new Dictionary<string, IModelBinder>();
                          foreach (var type in typeof(MessageModelBinderProvider).GetTypeInfo().Assembly.GetTypes())
                          {
                              var typeInfo = type.GetTypeInfo();
                              if (typeInfo.IsAbstract || typeInfo.IsNested)
                              {
                                  continue;
                              }
                  
                              if (!(typeInfo.IsClass && typeInfo.IsPublic))
                              {
                                  continue;
                              }
                  
                              if (!typeof(ICommand).IsAssignableFrom(type))
                              {
                                  continue;
                              }
                  
                              var metadata = context.MetadataProvider.GetMetadataForType(type);
                              var binder = context.CreateBinder(metadata);
                              binders.Add(type.FullName, binder);
                          }
                  
                          return new MessageModelBinder(context.MetadataProvider, binders);
                      }
                  }
                  

                  MessageModelBinder

                  public class MessageModelBinder : IModelBinder
                  {
                      private readonly IModelMetadataProvider _metadataProvider;
                      private readonly Dictionary<string, IModelBinder> _binders;
                  
                      public MessageModelBinder(IModelMetadataProvider metadataProvider, Dictionary<string, IModelBinder> binders)
                      {
                          _metadataProvider = metadataProvider;
                          _binders = binders;
                      }
                  
                      public async Task BindModelAsync(ModelBindingContext bindingContext)
                      {
                          var messageTypeModelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "messageType");
                          var messageTypeResult = bindingContext.ValueProvider.GetValue(messageTypeModelName);
                          if (messageTypeResult == ValueProviderResult.None)
                          {
                              bindingContext.Result = ModelBindingResult.Failed();
                              return;
                          }
                  
                          IModelBinder binder;
                          if (!_binders.TryGetValue(messageTypeResult.FirstValue, out binder))
                          {
                              bindingContext.Result = ModelBindingResult.Failed();
                              return;
                          }
                  
                          // Now know the type exists in the assembly.
                          var type = Type.GetType(messageTypeResult.FirstValue);
                          var metadata = _metadataProvider.GetMetadataForType(type);
                  
                          ModelBindingResult result;
                          using (bindingContext.EnterNestedScope(metadata, bindingContext.FieldName, bindingContext.ModelName, model: null))
                          {
                              await binder.BindModelAsync(bindingContext);
                              result = bindingContext.Result;
                          }
                  
                          bindingContext.Result = result;
                      }
                  }
                  

                  这篇关于asp net core rc2.抽象类模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Performance overhead of using attributes in .NET(在 .NET 中使用属性的性能开销)
                  Accessing attribute info from DTE(从 DTE 访问属性信息)
                  c# Hide a property in datagridview with datasource(c#使用数据源隐藏datagridview中的属性)
                  Extract Display name and description Attribute from within a HTML helper(从 HTML 帮助器中提取显示名称和描述属性)
                  C# Attributes and their uses(C# 属性及其用途)
                  C# - Getting all enums value by attribute(C# - 按属性获取所有枚举值)

                        <tfoot id='KxupL'></tfoot>

                          <tbody id='KxupL'></tbody>
                          • <bdo id='KxupL'></bdo><ul id='KxupL'></ul>
                            <legend id='KxupL'><style id='KxupL'><dir id='KxupL'><q id='KxupL'></q></dir></style></legend>

                            <small id='KxupL'></small><noframes id='KxupL'>

                            <i id='KxupL'><tr id='KxupL'><dt id='KxupL'><q id='KxupL'><span id='KxupL'><b id='KxupL'><form id='KxupL'><ins id='KxupL'></ins><ul id='KxupL'></ul><sub id='KxupL'></sub></form><legend id='KxupL'></legend><bdo id='KxupL'><pre id='KxupL'><center id='KxupL'></center></pre></bdo></b><th id='KxupL'></th></span></q></dt></tr></i><div id='KxupL'><tfoot id='KxupL'></tfoot><dl id='KxupL'><fieldset id='KxupL'></fieldset></dl></div>