prevent被覆盖补丁在.NET的Azure网络阿比某些字段 [英] Prevent certain fields from being overwritten with PATCH in .NET Azure Web Api
问题描述
我与.NET的后端,它使用一个TableController(ApiController的子类)来处理REST请求创建的Azure移动服务。
I am creating an Azure Mobile Service with a .NET backend which uses a TableController (subclass of ApiController) to handle REST requests.
在我的打补丁方法我想限制的组允许被更新的领域。我有一个的AccountController,我不想领域用户名
和用户ID
被覆盖。
In my PATCH method I want to restrict the set of fields that are allowed to be updated. I have an AccountController where I don't want the fields Username
and UserId
to be overwritten.
public class AccountController : TableController<Account>
{
...
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<Account> PatchAccount(string id, Delta<Account> patch)
{
return UpdateAsync(id, patch);
}
...
}
我想送回去就好有意义的HTTP响应403:禁止
或连接至API客户端尝试更新的用户名或用户id相似。所以,我需要或者知道增量补丁的内容或有当'禁止'字段更新自动应答的某种方式。
I would like to send back a meaningful HTTP response like 403: Forbidden
or similar if a client connecting to the API tries to update the username or userId. So I need some way of either knowing the content of the Delta patch or having an auto response when the 'forbidden' fields are being updated.
推荐答案
不知道是否有一个内置的方式做到这一点。但是,您可以解决此。创建新的属性,比方说不可编辑
。
Not sure if there is a built-in way to do that. However, you can workaround this. Create new attribute, let's say NonEditable
.
public class NonEditableAttribute: Attribute
{
}
应用这个属性,你不想被修补的属性。
Apply this attribute to properties you don't want to be patched.
public class Account
{
[NonEditable]
public string UserName {get;set;}
... other properties
}
写一些辅助方法,将检查对三角洲和LT更改的属性; T&GT;
包含任何这些非可编辑的属性。
Write some helper method that will check if changed properties on Delta<T>
contains any of these non editable properties.
public bool IsValidDelta<T>(Delta<T> delta) where T: class
{
// list of property names that can't be patched
var nonEditablePropertyNames = from p in typeof(T).GetProperties()
let attr = p.GetCustomAttribute(typeof(NonEditableAttribute))
where attr != null
select p.Name;
// list of property names that were changed
var changedPropertyNames = delta.GetChangedPropertyNames();
// check if changedPropertyNames contains any of propertyNames,
// if yes return false, if no return true;
}
现在,在你的ApiController,只是检查是否三角洲&LT; T&GT;
包含更改的属性,不可编辑
Now, in your ApiController, just check if Delta<T>
contains changed properties, that are not editable
public class AccountController : TableController<Account>
{
...
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<Account> PatchAccount(string id, Delta<Account> patch)
{
if(IsValidDelta(patch))
return UpdateAsync(id, patch);
else
// forbidden...
}
...
}
请注意: code未经过测试,可以更好的设计。这是给你的总体思路 - 把它当作伪code
Please Note: Code is not tested, and can be better designed. This is to give you general idea - treat it as pseudo code.
这篇关于prevent被覆盖补丁在.NET的Azure网络阿比某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!