【问题标题】:Can BindProperty extract data from posted JSON?BindProperty 可以从发布的 JSON 中提取数据吗?
【发布时间】:2022-11-21 16:53:55
【问题描述】:

ASP.NET Core 具有此 BindProperty 属性,您可以使用该属性将控制器级属性绑定到 HTTP 请求的参数。

[BindProperty (SupportsGet=true)]
public string Name { get; set; }

但是,它不会绑定到请求,如果它是 Content-Type: application.json 并且正文是:

{
    "name": "Somebody"
}

我们也可以将它配置为绑定到 JSON 吗?

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    请求体需要绑定一个复杂的模型,所以不能直接绑定string,如果要绑定这个值,这里有两种方法。

    第一种方法是创建一个包含此属性的类:

    public class Test
        {
            public string Name { get; set; }
        }
    

    然后在您的代码中绑定此类:

        [BindProperty]
        [FromBody]
        public Test test { get; set; }
    

    第二种方法是自定义模型绑定:

    public class MyBinder : IModelBinder
        {
            public async Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                    throw new ArgumentNullException(nameof(bindingContext));
    
                var modelName = bindingContext.FieldName;
    
                string bodyAsText = await new StreamReader(bindingContext.HttpContext.Request.Body).ReadToEndAsync();
                if (bodyAsText == null)
                {
                    return;
                }
                
                //check if the key equals fieldName
                var key = bodyAsText.Trim().Substring(12, modelName.Length);
                if (!modelName.Equals(key))
                {
                    return;
                }
    
                //get the value.
                var result = bodyAsText.Split(":")[1];
                var a = result.Substring(2, result.IndexOf("
    ") - 3);
    
                bindingContext.Result = ModelBindingResult.Success(a);
            }
        }
    

    然后你可以绑定一个字符串值:

    [BindProperty]
    [ModelBinder(BinderType = typeof(MyBinder))]
    public string Name { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2018-03-09
      • 2011-09-14
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多