Running code analysis on the following action results in a CA1062 warning, advising I validate the parameter before using it:
[HttpPost]
public ActionResult Index(SomeViewModel vm)
{
if (!ModelState.IsValid)
return View(vm);
// ... other code
return View(vm);
}
I realize I could resolve the warning by adding:
if(vm==null)
throw new ArgumentNullException("vm");
I was under the impression that if default model binding succeeded the incoming parameter could never be null and would not need to be validated beyond “ModelState.IsValid”.
- Is that the case?
- Is there a widely accepted technique for addressing this warning for MVC actions?
It is a public method, so you shouldn’t be making assumptions about who will be calling it. While one caller (the MVC framework) might only invoke the method with non-null values, other potential callers might not be quite so “polite”.
That said, if your code does not have other potential callers (which wouldn’t be unusual for an MVC application, as opposed to a library), allowing a NullReferenceException to be thrown instead of an ArgumentNullException might be perfectly acceptable. That would depend largely on your expectations for future use and maintainability of the code base. (Amongst other things, a future maintenance developer would probably find it easier to identify a problem if it’s signalled via an ArgumentNullException.)