Asp.Net MVC 5绑定参数完全来自正文 [英] Asp.Net MVC 5 bind parameter exclusively from body

查看:79
本文介绍了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]将完成此工作:

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/zh-CN/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天全站免登陆