Asp.Net WebApi 集成OWIN架构后,出现 “没有 OWIN 身份验证管理器与此请求相关联” 的解决办法

时间:2017-05-24 20:17:35   收藏:0   阅读:1122

在Asp.Net WebApi 项目中开启OWIN模块之后,如果没有在OWIN的Startup类中配置认证方式,调用WebApi的相关Controller和Action就会出现如下异常:

出现错误。
没有 OWIN 身份验证管理器与此请求相关联。
ExceptionType:System.InvalidOperationException
StackTrace:   在 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());
        }
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!