4

Consider the following sample:

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

The class TheModel has a custom ModelBinder named TheModelBinder. In this test, TheModelBinder decides what property/field to set based on the value of query string parameter named testMode.

Using a static Stopwatch, I started measuring the time between the end of model binding and the beginning of the action. Here are the approximate results:

If testMode == PropInfo then TheModelBinder sets value to a property of type PropertyInfo named PropInfo.
(This is pretty slow, around 800-1000 ms)

If testMode == FieldPropInfo then TheModelBinder sets value to a field of type PropertyInfo named PropInfoField.
(This one takes 0ms)

If testMode == BoxedPropInfo then TheModelBinder sets value to a property of type object named BoxedPropInfo.
(This one takes 0ms too)

Now the question is: Why the first testMode (setting the PropInfo property) increases the execution time (after the model bound successfully) up to 800-1000 milliseconds?

Tested on asp.net core 2.1 and 2.2 preview2

To test this yourself, you can do dotnet new webapi and paste the content of sample to a new file. If you run the app on port 5000, you can test the execution time using these URLs:

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

1 回答 1

4

如果您启用调试级别日志记录,并在刷新浏览器时密切监视日志,您可以看到使用时出现暂停的位置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'.

这是参数 binder 的模型验证。模型验证负责验证[Required]模型验证属性等内容。

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

然而,验证始终基于声明的模型类型,因此object不会扫描属性。验证也只适用于属性。这就是为什么该PropertyInfo属性是验证实际上需要时间的唯一情况。您还可以通过添加另一种MemberInfoPropertyInfo. 它的验证速度会比PropertyInfo案例快一点。


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

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

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

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

services.AddMvc(options =>
{
    // suppress child validation for `PropertyInfo` members
    options.ModelMetadataDetailsProviders.Add(
        new SuppressChildValidationMetadataProvider(typeof(PropertyInfo)));
});
于 2018-10-30T14:29:54.397 回答