asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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));

大佬总结

以上是大佬教程为你收集整理的asp.net – 没有使用WebApi委托处理程序分配内部处理程序全部内容,希望文章能够帮你解决asp.net – 没有使用WebApi委托处理程序分配内部处理程序所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。