在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' }
,请求应该失败,因为在我的情况下'Dummy'字段。 (异常或错误请求响应)
如何限制MVC Model Binder仅在某些方法上以这种方式运行?对于项目中的某些模型,此要求不适用于所有方法。
实现此要求的简便方法是检查Request.Form.Keys.Count != 2 or > 2
if (Request.Form.Keys.Count > 2)
{
return View("Error"); // handle error
}
else
{
// handle logic here
}
如果你可以使用Newtonsoft.JSON库,MissingMemberHandling property有JsonSerializerSettings
。您可以使用此属性编写自定义模型绑定器以从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)。
解决方案:
[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;
}