標籤:ack handler asa win challenge eof blog trace oci
在Asp.Net WebApi 項目中開啟OWIN模組之後,如果沒有在OWIN的Startup類中配置認證方式,調用WebApi的相關Controller和Action就會出現如下異常:
出現錯誤。沒有 OWIN 身分識別驗證管理器與此請求相關聯。ExceptionType:System.InvalidOperationExceptionStackTrace: 在 System.Web.Http.Owin.PassiveAuthenticationMessageHandler.SuppressDefaultAuthenticationChallenges(HttpRequestMessage request)在 System.Web.Http.Owin.PassiveAuthenticationMessageHandler.<SendAsync>d__0.MoveNext()--- 引發異常的上一位置中堆疊追蹤的末尾 ---在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)在 System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()
如果是英文版的VisualStudio,以上異常資訊會是:No OWIN authentication manager is associated with the request
原因是因為我們在Asp.Net WebApi項目使用了OWIN架構,但是沒有指定OWIN架構使用的認證方式,而WebApi又預設啟用了身份認證,所以WebApi無法認證到來的Http請求,拋出異常。
我們可以看到下面的OWIN架構Startup類的Configuration方法為空白,沒有為OWIN制定身份認證方式。
using System;using System.Collections.Generic;using System.Linq;using Microsoft.Owin;using Microsoft.Owin.Security;using Microsoft.Owin.Security.Cookies;using Owin;[assembly: OwinStartup(typeof(Daimler.CdnMgmt.Web.Startup))]namespace Daimler.CdnMgmt.Web{ public partial class Startup { public void Configuration(IAppBuilder app) { } }}
解決方案有兩個:
第一:在OWIN的Startup類中指定預設的認證方式。
using System;using System.Collections.Generic;using System.Linq;using Microsoft.Owin;using Microsoft.Owin.Security;using Microsoft.Owin.Security.Cookies;using Owin;[assembly: OwinStartup(typeof(Daimler.CdnMgmt.Web.Startup))]namespace Daimler.CdnMgmt.Web{ public partial class Startup { public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); } }}
Asp.Net WebApi 整合OWIN架構後,出現 “沒有 OWIN 身分識別驗證管理器與此請求相關聯” 的解決辦法