asp.net – 没有使用WebApi委托处理程序分配内部处理程序

我有一个WebApi在我的代码中抛出异常的问题:
public class WebApiAuthenticationHandler : DelegatingHandler
    {
        private const string AuthToken = "AUTH-TOKEN";

        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,CancellationToken cancellationToken)
        {                  
            var requestAuthTokenList = GetRequestAuthTokens(request);
            if (ValidAuthorization(requestAuthTokenList))
            {
                // EXCEPTION is occuring here!....
                return base.SendAsync(request,cancellationToken);
            }

            /*
            ** This will make the whole API protected by the API token.
            ** To only protect parts of the API then mark controllers/methods
            ** with the Authorize attribute and always return this:
            **
            ** return base.SendAsync(request,cancellationToken);
            */
            return Task<HttpResponseMessage>.Factory.StartNew(
                () =>
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = new StringContent("Authorization Failed")
                    };

                    //var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized);                                                                                   
                    //resp.Headers.Add(SuppressFormsAuthenticationRedirectModule.SuppressFormsHeaderName,"true");
                    return resp;
                });
        }

例外情况正在发生:

base.SendAsync(request,cancellationToken);

我不知道如何解决这个问题.我的路线表中有以下内容

routes.MapHttpRoute("NoAuthrequiredApi","api/auth/",new { Controller = "Auth" });
    routes.MapHttpRoute("DefaultApi","api/{controller}/{id}",new { id = RouteParameter.Optional },null,new WebApiAuthenticationHandler());

发生这种路由是DefaultApi路由.任何帮助非常感谢….

解决方法

找到答案 here一个示例处理程序 here.

您需要设置您希望传递的请求的InnerHandler.

只需将其添加到您的构造函数中即可:

public class WebApiAuthenticationHandler : DelegatingHandler
{
    public WebApiAuthenticationHandler(HttpConfiguration httpConfiguration)
    {
        InnerHandler = new HttpControllerdispatcher(httpConfiguration); 
    }

并在创建新实例时传递对GlobalConfiguration的引用:

routes.MapHttpRoute("DefaultApi",WebApiAuthenticationHandler(GlobalConfiguration.Configuration));

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....