Search code examples
asp.net-mvc-5xsssql-injection

MVC 5 security concern related to viewmodel XSS, SQL Injection


Can somebody please explain what exactly ModelState.IsValid means in a MVC action controller?

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Something(MyViewModel model)
    {            
       if (ModelState.IsValid)
        {

        }
    }

I know that ValidateAntiForgeryToken does some protection related to the form posting origin.

If a malicious user will bypass the form validation on the client side and manage to post some malicious code to my action method, will it be detected by ModelState.IsValid?

How can I best protect on the server side, once a form has been posted to my app?

Do I have to manually check the model that it doesn't contain XSS or SQL malicious code?

P.S.

I use EF Code First and I think is quite safe but want to be sure.


Solution

  • ModelState.IsValid means that all the validations etc which you have used in your model class is valid or not..

    for ex:-

     public class Emp
     {
        [Required]
        public int EmpCd { get; set; }
     }
    

    So if during post EmpCd has null or string value it will make ModelState as Invalid..

    This is basically used if you manage to avoid the UI unobtrusive client validation ,then ModelState.IsValid will validate.

    ModelState.IsValid tells you if any model errors have been added to ModelState.

    The default model binder will add some errors for basic type conversion issues (for example, passing a "string" for something which is an "int").

    The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.