如何在ASP.NET Web API中处理承载令牌的缺失或过期

时间:2019-05-02 10:46:14

标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api2

我有一个ASP.NET Web API,我想返回一个有意义的消息而不是此异常,以防 token 过期或请求中根本没有提供它。在这种情况下,这是我的例外。

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

预先感谢

1 个答案:

答案 0 :(得分:0)

感谢@Mark Wagoner的评论,我看到了这句话,但我以前没有注意到

  

在SomePath \ Controllers \ SomeController.cs:第21行

在第21行的控制器中,有以下行:

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

    public HttpResponseMessage Get()
    {
    ...

并且由于此处未提供令牌,因此可以预期,上一行将通过 Object reference未设置为object 异常的实例。我在方法外声明了它,因为它在多个方法中使用。因此,我从那里删除了它,并为每种方法声明了它,从而解决了我的问题。

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