ASP.NET MVC 拒绝其他字段



在 ASP.NET MVC中,我有HTTP方法

[HttpPost]
public JsonResult SampleMethod(LoginModel prmModel)
{
}

LoginModel是这样的:

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

如果请求正文的字段数超过预期(用户名和密码(,我希望请求失败

如果{Username: 'U', Password: 'P', Dummy:'D' } HTTP请求正文,则在我的情况下,由于"虚拟"字段,请求应该失败。(异常或错误请求响应(

如何限制 MVC 模型绑定器仅在某些方法上以这种方式运行?此要求并非适用于所有方法,也适用于项目中的某些模型。

如果可以使用 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(。

实现此要求的简单方法是检查Request.Form.Keys.Count != 2 or > 2

        if (Request.Form.Keys.Count > 2)
        {
            return View("Error"); // handle error
        }
        else
        {
            // handle logic here
        }

解决方案:

[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;
}

最新更新