删除 ASP MVC WebApi 操作方法中的 json 字段
Remove json field in ASP MVC WebApi Action Method
我有一个接受模型 UpdateProductCommand 的控制器,如下所示:
public IHttpActionResult UpdateProduct(UpdateProductCommand command)
{
command.AuditUserName = this.RequestContext.Principal.Identity.Name;
// ....
}
出于安全考虑,AuditUserName
字段不应设置在外部(来自 API 调用)。
如何从 JSON 请求中删除(或截断)该字段的值?
可以通过以下方式实现ModelBinder
:
using Newtonsoft.Json.Linq;
public class FieldRemoverModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
string content = actionContext.Request.Content.ReadAsStringAsync().Result;
JObject json = JObject.Parse(content);
JToken property = json.GetValue(bindingContext.ModelName, StringComparison.OrdinalIgnoreCase);
property?.Parent.Remove();
bindingContext.Model = json.ToObject(bindingContext.ModelType);
return true;
}
}
这样使用:
public IHttpActionResult UpdateProduct(([ModelBinder(typeof(FieldRemoverModelBinder), Name = nameof(UpdateProductCommand.AuditUserName))]UpdateProductCommand command)
{
// here command.AuditUserName will always be empty, no matter what's in json
这就是 DTO 的用途。
您可以创建另一个 class(例如 UpdateProductCommandDto
),它只包含您需要/想要用作输入的属性,然后您可以只使用 Automapper 将其映射到 UpdateProductCommand
.
的新实例
我有一个接受模型 UpdateProductCommand 的控制器,如下所示:
public IHttpActionResult UpdateProduct(UpdateProductCommand command)
{
command.AuditUserName = this.RequestContext.Principal.Identity.Name;
// ....
}
出于安全考虑,AuditUserName
字段不应设置在外部(来自 API 调用)。
如何从 JSON 请求中删除(或截断)该字段的值?
可以通过以下方式实现ModelBinder
:
using Newtonsoft.Json.Linq;
public class FieldRemoverModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
string content = actionContext.Request.Content.ReadAsStringAsync().Result;
JObject json = JObject.Parse(content);
JToken property = json.GetValue(bindingContext.ModelName, StringComparison.OrdinalIgnoreCase);
property?.Parent.Remove();
bindingContext.Model = json.ToObject(bindingContext.ModelType);
return true;
}
}
这样使用:
public IHttpActionResult UpdateProduct(([ModelBinder(typeof(FieldRemoverModelBinder), Name = nameof(UpdateProductCommand.AuditUserName))]UpdateProductCommand command)
{
// here command.AuditUserName will always be empty, no matter what's in json
这就是 DTO 的用途。
您可以创建另一个 class(例如 UpdateProductCommandDto
),它只包含您需要/想要用作输入的属性,然后您可以只使用 Automapper 将其映射到 UpdateProductCommand
.