【问题标题】:How do you access this property from the OwinStartup file?如何从 OwinStartup 文件访问此属性?
【发布时间】:2015-03-27 12:20:43
【问题描述】:

我正在创建一个 ASP.NET Identity 2.1 WebAPI 服务。它允许注册、登录和授权 authtokens。在 this tutorial 之后创建的 Owin 启动类中是以下代码:

public class OwinStartup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration httpConfig = new HttpConfiguration();

        ConfigureOAuthTokenGeneration(app);

        ConfigureWebApi(httpConfig);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        app.UseWebApi(httpConfig);
    }

    private void ConfigureOAuthTokenGeneration(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(AppDbContext.Create);
        app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);

        // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
    }

    private void ConfigureWebApi(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

现在,在 ConfigureOAuthTokenGeneration 方法中,创建了 DbContext 和 UserManager。我的问题:如何在我的 WepAPI 项目的不同类中访问这个 dbContext 和 UserManager?

【问题讨论】:

    标签: c# asp.net asp.net-web-api asp.net-identity-2


    【解决方案1】:
    AppDbContext context = HttpContext.Current.GetOwinContext().Get<AppDbContext>();
    AppUserManager userManager = HttpContext.Current.GetOwinContext().Get<AppUserManager();
    

    AccountController(在示例项目中)检索这些值的方式相同。

    【讨论】:

    • 谢谢。出于某种原因,这对我之前不起作用,但我想我必须重建我的项目。
    猜你喜欢
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 2014-06-22
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多