代码之家  ›  专栏  ›  技术社区  ›  Dennis K

天冬氨酸。Net MVC 5仅从主体绑定参数

  •  11
  • Dennis K  · 技术社区  · 9 年前

    我希望防止通过url查询字符串向MVC 5应用程序发布敏感数据。

    在MVC中 DefaultModelBinder 这个 默认模型活页夹 查找 ActionMethod url查询字符串中的参数、主体和路由。但我的目标是仅从身体和 来自路由或查询字符串。

    在Asp。NetWebApi有这样一个概念。属性[FromBody]将执行以下操作: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    有什么适合MVC的吗?

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

    3 回复  |  直到 9 年前
        1
  •  6
  •   Rafael Companhoni    9 年前

    默认情况下,绑定器在四个位置查找数据:表单数据、路由数据、查询字符串和任何上载的文件。

    可以将绑定限制为单个数据源。为此,您应致电 更新模型 方法作为第二个参数传递 表单值提供程序 对象( IValueProvider(值提供程序) ).

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

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

    • 表单值提供程序 :搜索正文中的数据(Request.Form)
    • 路由数据值提供程序 :搜索路由中的数据(RouteData.Value)
    • 查询字符串值提供程序 :在查询字符串(Request.QueryString)中搜索数据
    • HttpFileCollectionValueProvider :搜索上载的文件(Request.files)
        2
  •  5
  •   Maria Ines Parnisari    9 年前

    另一种方法:创建 自定义模型活页夹 使用 表单值提供程序 。这样做的优点是不必修改操作方法。

    例子:

    [ModelBinder(typeof(PersonBinder))]
    public class Person
    {
        [DisplayName("Social Security Number")]
        public int SSN { get; set; }
    
        [HiddenInput(DisplayValue = false)]
        public string ShouldNotBind { get; set; }
    }
    
    public class PersonBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            bindingContext.ValueProvider = new FormValueProvider(controllerContext);
            Person model = (Person)bindingContext.Model ?? new Person();
            model.SSN = Convert.ToInt16(GetValue(bindingContext, "SSN"));
            return model;
        }
    
        private string GetValue(ModelBindingContext context, string name)
        {
            ValueProviderResult result = context.ValueProvider.GetValue(name);
            if (result == null || result.AttemptedValue == "")
            {
                return "<Not Specified>";
            }
            return result.AttemptedValue;
        }
    }
    

    以及你的行动方法:

    [HttpPost]
    public ActionResult Person(Person person)
    {
        return View(person);
    }
    

    即使使用查询字符串发布 ShouldNotBind 属性将显示为“null”。

        3
  •  -1
  •   Piotr Dory    9 年前

    为什么不使用表单呢? 提交表单数据时