15

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ルートです。どんな助けでも大歓迎です...

4

2 に答える 2

36

ここで答えを見つけ、ここでハンドラーの例を見つけまし

リクエストを渡す InnerHandler を設定する必要があります。

これをコンストラクターに追加するだけです。

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

そして、新しいインスタンスを作成するときに GlobalConfiguration への参照を渡します。

routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }, null, WebApiAuthenticationHandler(GlobalConfiguration.Configuration));
于 2012-12-18T08:54:41.120 に答える
3

要求した RESTful URL が実際にコントローラーに存在するかどうかを確認する必要がある場合があります。間違った URL の一致が原因で、この種の例外に遭遇したことがあります。ありがとう。

于 2013-12-12T10:08:47.477 に答える