Asp.net web api ASP.Net WebAPI OWIN:为什么Request.GetOwinContext()会返回null?
在我的生产代码中,Request.GetOwinContext()总是返回null,这是一个问题 我设置了一个小型测试WebAPI控制器,以尝试隔离问题:Asp.net web api ASP.Net WebAPI OWIN:为什么Request.GetOwinContext()会返回null?,asp.net-web-api,owin,Asp.net Web Api,Owin,在我的生产代码中,Request.GetOwinContext()总是返回null,这是一个问题 我设置了一个小型测试WebAPI控制器,以尝试隔离问题: public class TestController : ApiController { [HttpGet] public async Task<IHttpActionResult> GetAsyncContext(string provider) { if (HttpContex
public class TestController : ApiController
{
[HttpGet]
public async Task<IHttpActionResult> GetAsyncContext(string provider)
{
if (HttpContext.Current.GetOwinContext() == null)
return this.BadRequest("No HttpContext.Current Owin Context");
if (Request.GetOwinContext() == null)
return this.BadRequest("No Owin Context");
return this.Ok();
}
[HttpGet]
public IHttpActionResult GetContext(string provider)
{
if (HttpContext.Current.GetOwinContext() == null)
return this.BadRequest("No HttpContext.Current Owin Context");
if (Request.GetOwinContext() == null)
return this.BadRequest("No Owin Context");
return this.Ok();
}
}
公共类TestController:ApiController
{
[HttpGet]
公共异步任务GetAsyncContext(字符串提供程序)
{
if(HttpContext.Current.GetOwinContext()==null)
返回此.BadRequest(“无HttpContext.Current Owin上下文”);
if(Request.GetOwinContext()==null)
返回此.BadRequest(“上下文中无Owin”);
返回这个;
}
[HttpGet]
公共IHttpActionResult GetContext(字符串提供程序)
{
if(HttpContext.Current.GetOwinContext()==null)
返回此.BadRequest(“无HttpContext.Current Owin上下文”);
if(Request.GetOwinContext()==null)
返回此.BadRequest(“上下文中无Owin”);
返回这个;
}
}
起初我认为这可能与异步运行的action方法有关,但在运行上述操作后,结果表明,在这两个版本中,Request.GetOwinContext()都返回null
我使用的是Microsoft.AspNet.WebApi.Owin.5.1.1(这似乎是定义GetOwinContext()扩展方法的地方)
你知道这里发生了什么吗?我遇到了类似的问题。要解决此问题,请确保ConfigureAuth中的Startup.Auth.cs文件中有以下行(通过调用方法CreatePerOwinContext) 方法 您的方法可能看起来像
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and role manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(
// clientId: "",
// clientSecret: "");
}
public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和角色管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationRoleManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
//使应用程序能够使用cookie存储登录用户的信息
//以及使用cookie临时存储用户登录第三方登录提供商的信息
//配置登录cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
Provider=新CookieAuthenticationProvider
{
//允许应用程序在用户登录时验证安全戳。
//这是一种安全功能,在您更改密码或向帐户添加外部登录时使用。
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
//允许应用程序在验证双因素身份验证过程中的第二个因素时临时存储用户信息。
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));
//使应用程序能够记住第二个登录验证因素,如电话或电子邮件。
//选中此选项后,登录过程中的第二步验证将在您登录的设备上被记住。
//这类似于登录时的RememberMe选项。
app.useTowFactoryMemberBrowserCookie(DefaultAuthenticationTypes.TwoFactoryRememberBrowserCookie);
//取消注释以下行以启用使用第三方登录提供程序登录
//app.UseMicrosoftAccountAuthentication(
//客户ID:“,
//客户机密:);
//app.UseTwitterAuthentication(
//消费市场:“,
//消费者信用:”;
//app.UseFacebookAuthentication(
//appId:“”,
//appSecret:”;
//app.UseGoogleAuthentication(
//客户ID:“,
//客户机密:);
}
另一个原因(尤其是在升级ASP.NET MVC4表单和/或空WebApi模板之后)是WebApi项目根目录中缺少Startup.cs文件
另外,请确保已安装Microsoft.Owin.Host.SystemWeb软件包
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(TestMVC5.Startup))]
namespace TestMVC5
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
您确定正在调用startup类并注册所有模块吗?我的修复程序是使用Nuget安装Microsoft.Owin.Host.SystemWeb。不要为我修复问题。当前上下文中不存在ApplicationRoleManager