在一个web api odata控制器中,我如何保护一些字段不被客户端更新

本文关键字:保护 何保护 字段 更新 客户端 web 一个 api odata 控制器 | 更新日期: 2023-09-27 18:29:48

我正试图了解web api odata控制器。

我如何修改我的控制器,使数据可以是:

  1. 由客户在提交表格时更新
  2. 保持不变(数据不需要更新)
  3. 使用服务器端值更新(客户端不应能够编辑此值)
  4. 只有在安全级别允许的情况下才更新

我的视图模型:

    public class Order
{
    [Key]
    // left unchanged
    public int OrderID { get; set; }
    // updated by the client when they submit a form
    public DateTime OrderDate { get; set; }
    // updated by the client when they submit a form
    public string OrderStatus { get; set; }
    // only updated if their security level allows it (left unchanged or may be updated by the client)
    public string ApprovalStatus { get; set; }
    // updated by the client when they submit a form
    public string OrderNotes { get; set; }
    // updated by the client when they submit a form
    public string PrivateNotes { get; set; }
    // updated using a server side value 
    public double OrderTotal { get; set; }
    // updated using a server side value 
    public string CreatedBy { get; set; }
    // left unchanged
    public DateTime CreatedDate { get; set; }
    // updated using a server side value 
    public DateTime ModifiedDate { get; set; }
    // updated using a server side value 
    public int? Active { get; set; }
    // updated by the client when they submit a form
    public int? CreditorID { get; set; }
    public virtual Creditor Creditor { get; set; }
}

我的控制器:

    // PATCH: odata/Orders(5)
    [AcceptVerbs("PATCH", "MERGE")]
    public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Order> patch)
    {
        Validate(patch.GetEntity());
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        Order order = await db.Orders.FindAsync(key);
        if (order == null)
        {
            return NotFound();
        }
        patch.Patch(order);
        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!OrderExists(key))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }
        return Updated(order);
    }

在一个web api odata控制器中,我如何保护一些字段不被客户端更新

您可以创建一个自定义属性,并用它装饰字段。请参阅此StackOverflow答案。