简体   繁体   中英

How to prevent a property from being set through model binding in ASP.NET Core Web API?

I've the following ZapScan class with a TargetUrl property whose purpose is to return the concatenation of the Url and Path properties.

The ZapScan class is also used as a parameter in a controller action, and thus is subject to model binding:

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

How can I prevent the TargetUrl property from being subject to model binding? Is it sufficient that it's a read-only property? What about the general case, where the property is also set-able?

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] attribute : I've been looking at the Bind attribute, but it doesn't appear to have a an Exclude property in ASP.NET Core Web API?

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

Maybe a private setter on TargetUrl can help :

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

    private set;
}

On the other hand, given that you are saying the framework to consume json, maybe just a JsonIgnore will do the trick

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

If the property is settable you can use [BindNever] on it. Like so:

using Microsoft.AspNetCore.Mvc.ModelBinding;

public class ZapScan
{
    // ...

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

    // ...
}

Here are the Microsoft docs explaining it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM