ASP.Net WebAPI OWIN:为什么Request.GetOwinContext()会返回null?

时间:2014-04-23 18:20:41

标签: asp.net-web-api owin

在我的生产代码中,我们遇到的问题是Request.GetOwinContext()总是返回null。

我设置了一个小型测试WebAPI控制器来尝试找出问题:

    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();
    }
}

起初我以为它可能与异步运行的action方法有关,但是在运行上面的内容之后,事实证明在两个版本中,Request.GetOwinContext()都返回null。

我正在使用Microsoft.AspNet.WebApi.Owin.5.1.1(这似乎是GetOwinContext()扩展方法的定义)。

关于这里发生了什么的任何想法???

2 个答案:

答案 0 :(得分:13)

另一个原因(特别是在升级ASP.NET MVC4和/或Empty WebApi Template之后)缺少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);
        }
    }
}

答案 1 :(得分:4)

我遇到过类似的问题。要解决此问题,请确保 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: "");
    }