Asp.Net MVC 5 bind parameter exclusively from body

后端 未结 3 1498
忘掉有多难
忘掉有多难 2020-12-16 01:40

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

In MVC there is a DefaultModelBinder. The DefaultModelBinder

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 01:46

    Another way: create a custom model binder that uses FormValueProvider. The advantage of this is that you don't have to modify the action method.

    Example:

    [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 "";
            }
            return result.AttemptedValue;
        }
    }
    

    And your action method:

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

    Even if you post with a querystring, the ShouldNotBind property will show as "null".

提交回复
热议问题