【问题标题】:How to prevent a property from being set through model binding in ASP.NET Core Web API?如何防止通过 ASP.NET Core Web API 中的模型绑定设置属性?
【发布时间】:2020-04-13 01:11:27
【问题描述】:

我有以下带有TargetUrl 属性的ZapScan 类,其目的是返回UrlPath 属性的串联。

ZapScan 类也用作控制器操作中的参数,因此受模型绑定:

[HttpPost, FormatFilter]
    [Consumes("application/json", new string[]{"application/xml"})]
    public ActionResult<ZapScan> OnPost([FromBody] ZapScan scan)
    {
        return HandleRequest(scan);
    }

如何防止TargetUrl 属性受到模型绑定?它是只读属性就足够了吗?那么一般情况下,属性也是可设置的呢?

public class ZapScan
{
   private string _url;
   private string _path;


   [XmlElement(IsNullable = true)]
   public string Url
   {
       get
       {
           return _url;
       }
       set
       {
           if (value is null)
           {
               throw new ArgumentNullException();
           }

           _url = value.EndsWith("/", StringComparison.Ordinal) ? value.Remove(value.Length - 1) : value;
       }
   }
   [XmlElement(IsNullable = true)]
   public string Path
   {
       get
       {
           return _path;
       }
       set
       {
           if (value is null)
           {
               _path = "";
           }
           else
           {
               _path = value.StartsWith("/", StringComparison.Ordinal) ? value : value.Remove(value.Length - 1);
           }
       }
   }
   public ScanType Type { get; set; } = ScanType.Active;

   public string TargetUrl
   {
       get
       {
           return Url + Path;
       }
   }

   public override string ToString() {
       return JsonSerializer.Serialize(this).ToLower();
   }
}

[绑定]属性: 我一直在查看 Bind 属性,但它似乎在 ASP.NET Core Web API 中没有 Exclude 属性?

[Bind(Exclude = "Height, Width")]

【问题讨论】:

  • 这能回答你的问题吗? Prevent Property from being serialized
  • 我相信您可以在该属性上使用 [BindNever] 属性。
  • 如果你使用实体框架,你可以使用 [NotMapped] 属性
  • @HereticMonkey - XmlIgnore 不是只适用于序列化而不适用于数据绑定吗?

标签: c# asp.net asp.net-core


【解决方案1】:

也许 TargetUrl 上的私人设置器可以提供帮助:

public string TargetUrl
{
    get
    {
        return Url + Path;
    }

    private set;
}

另一方面,鉴于您说的是使用 json 的框架,也许只需要一个 JsonIgnore 就可以了

[JsonIgnore]
public string TargetUrl
{
    get
    {
        return Url + Path;
    }
}

【讨论】:

  • 我相信没有集合类似于只读而不是私有。我知道 readonly 比 private 更严格,但我认为这在过去对我有用。
猜你喜欢
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2020-01-28
  • 2016-08-16
  • 2021-05-09
  • 2022-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多