Note that there are some explanatory texts on larger screens.

plurals
  1. POIgnore exceptions caused by missing controller parameters
    primarykey
    data
    text
    <p>I have an internet-facing website that's built using MVC4 and I occasionally get error reports from bots or curious users who send requests for incomplete URLs.</p> <p>For example:</p> <pre><code>public class ProductController : Controller { [HttpGet] public void View(int id) { // ... </code></pre> <ul> <li>A GET request to <code>/product/view/1</code> is valid.</li> <li>A GET request to <code>/product/view</code> is invalid as the argument is not specified.</li> </ul> <p>Such invalid requests raise exceptions resembling:</p> <pre><code>System.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult View(Int32)' in 'Foo.ProductController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters at System.Web.Mvc.ActionDescriptor.ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary`2 parameters, MethodInfo methodInfo) at System.Web.Mvc.ReflectedActionDescriptor.&lt;&gt;c__DisplayClass1.&lt;Execute&gt;b__0(ParameterInfo parameterInfo) ... </code></pre> <p>As the exception message states, I could make the <code>id</code> argument nullable and check within the action method, but I have <em>many</em> controllers with <em>many</em> actions.</p> <p>I'd like to return a <code>BadRequest</code>/<code>NotFound</code> response to any request that fails to bind arguments to action parameters, and specify this in a single place in code to apply across all controllers.</p> <p>How can this be done?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload