BindAttribute doesn't seem to work in ASP.Net MVC Core (2.0.8)

会有一股神秘感。 提交于 2020-01-25 09:12:28

问题


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).

This is what I tried.

Model:

[Bind("One")]
public class SomeModel 
{
    public int One { get; set; }
    public int Two { get; set; }
}

Controller method:

[HttpPost("foo")]
[Consumes("application/json")]
public IActionResult Foo([FromBody] SomeModel model)
{
    return Json(model);
}

What I'm sending in POST:

{
    "One": 1,
    "Two": 2
}

Response I'm getting:

{
    "One": 1,
    "Two": 2
}

I also tried putting the [Bind] attribute right before the controller method parameter, but it doesn't work.

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.

Am I doing something wrong?


回答1:


It seems [Bind] doesn't work for JSON, so there's no way around this, at least for my use case.

See: https://github.com/aspnet/Mvc/issues/8005 and https://github.com/aspnet/Mvc/issues/5731




回答2:


The [Bind] attribute must be on the parameter. You cannot define it at a class level. The reason @Nkosi's suggestion failed is that you still also need [FromBody] since you're posting JSON. In other words:

[HttpPost("foo")]
[Consumes("application/json")]
public IActionResult Foo([FromBody][Bind("One")] SomeModel model)
{
    return Json(model);
}

FWIW, whoever setup you static analysis is a moron and should be called such, repeatedly and with much vigor.




回答3:


It seems that the BindAttribute doesn't work as expected when the model is passed via the body in the request. When it's passed via the QueryString, then it works as expected.

You can test this out using the following sample code:

This is the model:

[Bind(include: nameof(MinX))]
public class ValueModel
{
    [JsonProperty("min-x")]
    public string MinX { get; set; }

    [JsonProperty("min-y")]
    public string MinY { get; set; }
}

The API methods where it works as expected:

[HttpGet()]
public ActionResult<string> Get([FromQuery] ValueModel value)
{
    return new OkObjectResult($"MinX={value.MinX}; MinY={value.MinY}");
}

[HttpPost]
public ActionResult Post([FromQuery]ValueModel value)
{
    return new OkObjectResult($"MinX={value.MinX}; MinY={value.MinY}");
}

The API methods where it doesn't work as expected:

[HttpPost]
public ActionResult Post([FromBody]ValueModel value)
{
    return new OkObjectResult($"MinX={value.MinX}; MinY={value.MinY}");
}


来源:https://stackoverflow.com/questions/51143055/bindattribute-doesnt-seem-to-work-in-asp-net-mvc-core-2-0-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!