zony.me

ASP.NET MVC 在上下文中找不到 owin.Environment 项。

英文则是:No owin.Environment item was found in the context 这个错误源自于:

C#
private IAuthenticationManager AuthenticationManager { 
    get {
            return HttpContext.GetOwinContext().Authentication;
        }
}

使用的是ASP.NET Identity身份认证系统,在使用AuthenticationManager的时候,发生了一个异常。提示“在上下文中找不到 owin.Environment 项”,百度谷歌半天无果。 之后感觉是自己缺少Startup类的原因,在项目根目录加入了一个cs文件,代码如下:

C#
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(NovelSite.Startup))]
namespace NovelSite
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

运行,仍然抛出异常,按照ASP.NET Identity登录原理一文中所说:

每一个OWin的应用程序都需要有一个start up的类,用来声明我们要使用的OWin组件(即中间件)。Start up 类有以下几种声明方式。

[assembly: OwinStartup(typeof(StartupDemo.TestStartup))]

之后仔细看了一下AutomaticAppStartup的意思,这个是OWIN的自动发现,结果是false关闭,删掉这条之后,成功运行。

ASP.NET MVC 在上下文中找不到 owin.Environment 项。
作者 Zony · 发布于 2016-08-11
Licensed under CC BY-NC-SA 4.0
← 上一篇ASP.NET + 使用Mysql作为数据库下一篇 →互斥锁与自旋锁