Skip to content

Instantly share code, notes, and snippets.

@BenjaminAdams
Created October 13, 2016 18:20
Show Gist options
  • Save BenjaminAdams/b05f75068f7df9b3cf7cef8909d20c50 to your computer and use it in GitHub Desktop.
Save BenjaminAdams/b05f75068f7df9b3cf7cef8909d20c50 to your computer and use it in GitHub Desktop.
c# Checks all incoming parameters for null in a WebApi Controller
using System;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Payments.Productization.Process.FilterAttributes
{
[AttributeUsage(AttributeTargets.Class)]
public class CheckModelForNullAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
if (context == null) throw new ArgumentNullException("Input Payload was malformed, invalid, or empty");
foreach (var arg in context.ActionArguments)
{
if (arg.Value == null)
{
throw new ArgumentException("Input Payload was malformed, invalid, or empty", arg.Key);
}
}
base.OnActionExecuting(context);
}
}
}
@BenjaminAdams
Copy link
Author

Inside of every API route we had a null check for all the parameters in the controller route function. Decided to move all that code to one place

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment