【问题标题】:High execution time when a property of type PropertyInfo being set on model in a custom model binder在自定义模型绑定器中的模型上设置 PropertyInfo 类型的属性时执行时间长
【发布时间】:2018-10-30 11:57:23
【问题描述】:

考虑以下示例:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace WebApiApp.Controllers
{
    public class TheModelFields
    {
        public int Id { get; set; }
    }

    [ModelBinder(typeof(TheModelBinder))]
    public class TheModel
    {
        public PropertyInfo PropInfo { get; set; }
        public PropertyInfo FieldPropInfo;
        public object BoxedPropInfo { get; set; }
    }

    enum TestMode
    {
        PropInfo,
        FieldPropInfo,
        BoxedPropInfo
    }

    public class TheModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.HttpContext.Request.Query.TryGetValue("testMode", out var modeStr) && Enum.TryParse(typeof(TestMode), modeStr, true, out var mode))
            {
                var model = new TheModel();
                var propInfo = typeof(TheModelFields).GetProperty("Id");

                switch (mode)
                {
                    case TestMode.PropInfo:
                        model.PropInfo = propInfo;
                        break;
                    case TestMode.FieldPropInfo:
                        model.FieldPropInfo = propInfo;
                        break;
                    case TestMode.BoxedPropInfo:
                        model.BoxedPropInfo = propInfo;
                        break;
                }

                bindingContext.Result = ModelBindingResult.Success(model);
                Timer.Stopwatch.Restart();
                return Task.CompletedTask;
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Failed();
                return Task.CompletedTask;
            }
        }
    }

    public static class Timer
    {
        public static Stopwatch Stopwatch = new Stopwatch();
    }

    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet("test")]
        public IActionResult Test([FromQuery]TheModel model)
        {
            Timer.Stopwatch.Stop();
            if (model is null)
                return BadRequest("pass testMode=PropInfo|FieldPropInfo|BoxedPropInfo for test");
            else
                return Ok($"Time: {Timer.Stopwatch.ElapsedMilliseconds}");
        }
    }
}

TheModel 类有一个名为 TheModelBinder 的自定义 ModelBinder。 在这个测试中,TheModelBinder 根据名为 testMode 的查询字符串参数的值来决定设置什么属性/字段。

使用静态秒表,我开始测量模型绑定结束和动作开始之间的时间。以下是大致结果:

如果testMode == PropInfoTheModelBinder 将值设置为PropertyInfo 类型的属性,名为PropInfo
(这很慢,大约 800-1000 毫秒)

如果 testMode == FieldPropInfoTheModelBinder 将值设置为类型为 PropertyInfo 的字段,名为 PropInfoField
(这个需要0ms)

如果testMode == BoxedPropInfoTheModelBinder 将值设置为名为@9​​87654336@ 的对象类型的属性。
(这个也需要0ms)

现在的问题是:为什么第一个 testMode(设置PropInfo 属性)会将执行时间(模型绑定成功后)增加到 800-1000 毫秒?

在 asp.net core 2.1 和 2.2 preview2 上测试

要自己测试,您可以执行dotnet new webapi 并将示例内容粘贴到新文件中。如果您在端口 5000 上运行应用程序,您可以使用这些 URL 测试执行时间:

  • http://localhost:5000/test?testMode=propInfo
  • http://localhost:5000/test?testMode=propInfoField
  • http://localhost:5000/test?testMode=boxedPropInfo

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    如果您启用调试级别日志记录,并在刷新浏览器时密切监视日志,您可以看到使用testMode=propInfo 时发生暂停的位置:

    dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[26]
          Attempting to validate the bound parameter 'model' of type 'Q53063808.Controllers.TheModel' ...
    dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder[27]
          Done attempting to validate the bound parameter 'model' of type 'Q53063808.Controllers.TheModel'.
    

    这是model validation of the parameter binder。模型验证负责验证 [Required] 模型验证属性等内容。

    为了使验证支持任意模型结构,它本质上会递归地扫描模型类型并尝试验证每一个属性。由于PropertyInfo 是一个相当大的类型,因此验证所有属性需要一些时间——即使没有要验证的内容。

    然而,验证始终基于声明的模型类型,因此不会扫描object 属性。验证也只适用于属性。这就是为什么 PropertyInfo 属性是唯一需要时间验证的情况。您还可以通过为MemberInfo 添加比PropertyInfo 小一点的另一个类型来确认这一点。它的验证速度比PropertyInfo 的情况要快一些。


    您不能真正选择性地禁用模型验证(例如,使用某些 SkipValidation 属性)。但是,您可以从模型绑定器中指定不应该为模型运行验证。这是通过为其设置验证状态来抑制验证来完成的:

    bindingContext.ValidationState.Add(model, new ValidationStateEntry { SuppressValidation = true });
    bindingContext.Result = ModelBindingResult.Success(model);
    

    这将完全跳过模型的验证,因此时间也应该下降到大约为零。

    或者,您还可以将 MVC 配置为在您的模型类型中找到 PropertyInfo 成员时禁止对子成员进行验证。为此,您需要在 Startup 的 ConfigureServices 中添加以下配置:

    services.AddMvc(options =>
    {
        // suppress child validation for `PropertyInfo` members
        options.ModelMetadataDetailsProviders.Add(
            new SuppressChildValidationMetadataProvider(typeof(PropertyInfo)));
    });
    

    【讨论】:

    • ModelBinding 的日志本身没有时间,我们确定是这样吗?
    • @ShahriarGholami 是的,非常确定。您可以实现并注册一个自定义 IObjectModelValidator,它什么都不做,并且在所有情况下,OP 代码中的时间都减少到零。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多