如何处理 ASP.NET Web API 中不记名令牌的缺失或过期

How to handle the absence or expiration of bearer token in ASP.NET Web API

我有一个 ASP.NET 网络 API,我想 return 一个有意义的消息而不是这个异常,以防 令牌 已过期或根本未在请求中提供。这是我在这种情况下遇到的例外情况。

{
    "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.<SendAsync>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)"
    }
}

我试过这样加了一个断点,但它甚至没有到达,所以我不知道我应该在哪里写代码来处理这个问题。

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;
    }
}

提前致谢

感谢@Mark Wagoner 的评论,我在之前没有注意到的异常中看到了这句话

in SomePath\Controllers\SomeController.cs:line 21

在第21行的controller中,有这一行:

    ...    
    string variable = ClaimsPrincipal.Current.FindFirst("SomeValue").Value;

    public HttpResponseMessage Get()
    {
    ...

并且由于此处未提供令牌,因此可以预期上面的行将通过 Object reference not set to an instance of an object 异常。我在方法外声明它,因为它在多个方法中使用。所以,我从那里删除它并为每个方法声明它并解决了我的问题。

我不知道的是,我在方法之外的控制器中声明的变量是先声明的,然后它开始执行自定义授权中的代码CustomAuthorizeAttribute : AuthorizeAttribute class .