title: How to handle the absence or expiration of bearer token in ASP.NET Web API
body: <p>I have an ASP.NET web API and I want to return a meaningful message instead of this exception in case if the <em>token</em> was expired or it wasn't provided in the request at all. This is the exception that I'm getting in this case.</p>
  
  <pre><code>{
      "Message": "An error has occurred.",
      "ExceptionMessage": "An error occurred when trying to create a controller of type 'SomeController'. Make sure that the controller has a parameterless public constructor.",
      "ExceptionType": "System.InvalidOperationException",
      "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.&lt;SendAsync&gt;d__1.MoveNext()",
      "InnerException": {
          "Message": "An error has occurred.",
          "ExceptionMessage": "Object reference not set to an instance of an object.",
          "ExceptionType": "System.NullReferenceException",
          "StackTrace": "   at WebApi.Controllers.SomeController..ctor() in SomePath\\Controllers\\SomeController.cs:line 21\r\n   at lambda_method(Closure )\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
      }
  }
  </code></pre>
  
  <p>I have tried like this and added a breakpoint, but it doesn't even reach it, so I'm not sure where should I write the code to handle this.</p>
  
  <pre><code>public override void OnAuthorization(HttpActionContext actionContext)
  {
      JsonHelper jsonHelper = new JsonHelper();
      if (actionContext == null)
      {
          actionContext.Response = jsonHelper.setHttpResponseMessage(jsonHelper.setResponse(false, null, "Expired or Incorrect token."));
          return;
      }
  }
  </code></pre>
  
  <p>Thanks in advance</p>