Asp.Net MVC 5 仅从正文绑定参数 [英] Asp.Net MVC 5 bind parameter exclusively from body

查看:34
本文介绍了Asp.Net MVC 5 仅从正文绑定参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想防止通过 url 查询字符串将敏感数据发布到 MVC 5 应用程序.

I want to prevent posting sensitive data via url query string to a MVC 5 application.

在 MVC 中有一个 DefaultModelBinder.DefaultModelBinder 在 url 查询字符串、主体和路由中查找 ActionMethod 参数.但我的目标是仅从正文中绑定参数,而从路由或查询字符串中绑定.

In MVC there is a DefaultModelBinder. The DefaultModelBinder looks for the ActionMethod parameters in the url query string, the body and the route. But my target is to bind the parameters exclusively from the body and not from route or query string.

在Asp.Net WebApi 中有这样一个概念.属性 [FromBody] 将完成这项工作:http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

In Asp.Net WebApi there is such a concept. The Attribute [FromBody] will do the job: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

有适合​​ MVC 的东西吗?

Is there something suitable for MVC?

我找到了 System.Web.ModelBinding.FormAttribute(https://msdn.microsoft.com/en-us/library/system.web.modelbinding.formattribute(v=vs.110).aspx).但是,如果我修饰了参数,它对模型绑定没有影响.

I´ve found the System.Web.ModelBinding.FormAttribute (https://msdn.microsoft.com/en-us/library/system.web.modelbinding.formattribute(v=vs.110).aspx). However, if I decorate the parameter, it has no effect to the model binding.

推荐答案

默认情况下,活页夹在四个位置查找数据:表单数据、路由数据、查询字符串和任何上传的文件.

By default, the binder looks for data in four places: form data, route data, the query string, and any uploaded files.

可以将绑定限制为单一数据源.为此,您应该调用 UpdateModel 方法,传递作为第二个参数的 FormValueProvider 对象(IValueProvider 的实现).

It is possible to restrict the binding to a single source of data. To do so you should call the UpdateModel method passing, as the second parameter, a FormValueProvider object( an implementation of IValueProvider).

public ActionResult Products()
{
    IList<Products> products = new List<Products>();
    UpdateModel(products, new FormValueProvider(ControllerContext));
    return View(products);
}

对象的完整列表是(它们都接收 ControllerContext 作为构造函数参数):

The complete list of objects is (they all receive the ControllerContext as the contructor parameter):

  • FormValueProvider:在正文(Request.Form)中搜索数据
  • RouteDataValueProvider:搜索路由中的数据(RouteData.Value)
  • QueryStringValueProvider:在查询字符串(Request.QueryString)中搜索数据
  • HttpFileCollectionValueProvider:搜索上传的文件 (Request.Files)
  • FormValueProvider: search for data in the body (Request.Form)
  • RouteDataValueProvider: search for data in the route (RouteData.Value)
  • QueryStringValueProvider: search for data in the query string (Request.QueryString)
  • HttpFileCollectionValueProvider: search for uploaded files (Request.Files)

这篇关于Asp.Net MVC 5 仅从正文绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆