[英]ASP.NET MVC Reject On Additional Fields
在ASP.NET MVC中,我有HTTP方法
[HttpPost]
public JsonResult SampleMethod(LoginModel prmModel)
{
}
和LoginModel一样:
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
如果请求正文中的字段比预期的多(用户名和密码),我希望请求失败
如果HTTP请求正文为{Username: 'U', Password: 'P', Dummy:'D' }
,由于我的情况为“虚拟对象”字段,请求应失败。 (异常或错误请求响应)
如何限制MVC Model Binder仅在某些方法上具有这种行为? 对于项目中的某些模型,此要求并非适用于所有方法。
解决方案:
[HttpPost]
public JsonResult SampleMethod()
{
dynamic prmModel= System.Web.Helpers.Json.Decode((new StreamReader(Request.InputStream).ReadToEnd()));
Newtonsoft.Json.Schema.JsonSchema schema = JsonSchema.Parse(Jsonschema());
Newtonsoft.Json.Linq.JObject user = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(prmModel));
if (!user.IsValid(schema) || user.Count > 2)
return Json("Bad Request");
}
public string Jsonschema()
{
string schemaJson = @"{
'description': 'A',
'type': 'object',
'properties': {
'UserName':{'type':'string'},
'Password':{'type':'string'}
}
}";
return schemaJson;
}
实现此要求的简单方法是检查Request.Form.Keys.Count != 2 or > 2
if (Request.Form.Keys.Count > 2)
{
return View("Error"); // handle error
}
else
{
// handle logic here
}
如果可以使用Newtonsoft.JSON库,则JsonSerializerSettings
有MissingMemberHandling属性 。 您可以编写自定义模型绑定程序,以使用此属性从json反序列化对象,如下所示:
public class StrictJsonBodyModelBinder : IModelBinder
{
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(string))
{
if (bindingContext.HttpContext.Request.ContentType != "application/json")
{
throw new Exception("invalid content type, application/json is expected");
}
using (var bodyStreamReader = new StreamReader(bindingContext.HttpContext.Request.Body))
{
var jsonBody = await bodyStreamReader.ReadToEndAsync().ConfigureAwait(false);
var jsonSerializerSettings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error,
};
var model = JsonConvert.DeserializeObject(jsonBody, bindingContext.ModelType, jsonSerializerSettings);
bindingContext.Result = ModelBindingResult.Success(model);
}
}
}
}
然后,可以将此模型绑定程序与ModelBinderAttribute
用于特定的操作参数:
[HttpPost]
public JsonResult SampleMethod([ModelBinder(typeof(StrictJsonBodyModelBinder))] LoginModel prmModel)
{
}
现在,当将传递无效属性时, JsonConvert
将引发错误(如果不会处理错误,将为用户使用HTTP 500)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.