【问题标题】:how to exclude an attribute using model binding in a controller in asp.net core web api如何在asp.net core web api的控制器中使用模型绑定排除属性
【发布时间】:2020-01-28 04:19:05
【问题描述】:

您好,当我在控制器 (Web API) 中执行操作时,我很想从我的模型中排除一个属性,

我试过[Bind(Exclude ="something")],但它似乎不是.net core api的一部分

【问题讨论】:

  • iirc [Bind] 仅适用于多部分/表单(MVC 操作),不适用于使用 json/xml 有效负载的 WebAPi。但是,如果您使用正确的 ViewModel 类(它们应该只包含特定操作所需的值),则根本不需要排除

标签: asp.net-core asp.net-web-api model-binding


【解决方案1】:

如果您使用的是 ASP.NET Core,请使用 Microsoft.AspNetCore.Mvc.ModelBinding.BindNeverAttribute 属性 ([BindNever])。

public class ExampleViewModel
{
    // ResponseMessage will not participate in model binding.

    [BindNever]
    public string ResponseMessage { get; set; }
}

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.bindneverattribute?view=aspnetcore-5.0

“表示应从模型绑定中排除属性。当应用于属性时,模型绑定系统会排除该属性。当应用于类型时,模型绑定系统会排除该类型定义的所有属性。”

【讨论】:

    【解决方案2】:

    [Bind] 属性不适用于 web api 如果您收到模型为 json,请尝试在需要排除的模型属性上使用 [JsonIgnore]

    public class MyModel
    {
        [JsonIgnore]
        public string Name { get; set; }
        //...
    }
    

    行动:

    [HttpPost]
    public IActionResult Student([FromBody]MyModel model)
    

    【讨论】:

      【解决方案3】:

      您可以使用 ViewModel 并将您的视图与模型绑定器绑定,但如果您想要排除的字段不为空,那么您的模型状态验证不会失败

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-13
        • 2014-06-05
        • 2020-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        相关资源
        最近更新 更多