BindAttribute在ASP.Net MVC Core(2.0.8)中似乎不起作用 [英] BindAttribute doesn't seem to work in ASP.Net MVC Core (2.0.8)
问题描述
我正在尝试使用Bind属性在模型中仅包括特定属性.我知道我可以使用视图模型并仅指定所需的属性,但是我不能使用它,因为代码必须经过一些静态代码分析,如果没有Bind属性,该分析会触发错误,并且我可以不能更改该规则(不受我控制).
I'm trying to use the Bind attribute to include only specific properties in my model. I know I can use a view model and only specify the properties I need, but I can't use that because the code has to run through some static code analysis that triggers an error if the Bind attribute is not present, and I can't change that rule (it's not controlled by me).
这是我尝试过的.
型号:
[Bind("One")]
public class SomeModel
{
public int One { get; set; }
public int Two { get; set; }
}
控制器方法:
[HttpPost("foo")]
[Consumes("application/json")]
public IActionResult Foo([FromBody] SomeModel model)
{
return Json(model);
}
我在POST中发送的内容:
What I'm sending in POST:
{
"One": 1,
"Two": 2
}
我得到的答复:
{
"One": 1,
"Two": 2
}
我还尝试将[Bind]
属性放在控制器方法参数的前面,但这不起作用.
I also tried putting the [Bind]
attribute right before the controller method parameter, but it doesn't work.
所以,我遇到的问题是,即使我明确告诉我只希望将"One"绑定,"Two"仍然会被分配一个值.
So, the problem I'm having is that "Two" still gets assigned a value, even though I explicitly told that I only want "One" to be bound.
我做错什么了吗?
推荐答案
看来[Bind]
不适用于JSON,因此,至少在我的用例中,没有办法解决此问题.
It seems [Bind]
doesn't work for JSON, so there's no way around this, at least for my use case.
请参阅: https://github.com/aspnet/Mvc/issues/8005和 https://github.com/aspnet/Mvc/issues/5731
这篇关于BindAttribute在ASP.Net MVC Core(2.0.8)中似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!