Startup类是如何发挥作用的?

时间:2014-04-25 01:27:48

标签: c# asp.net asp.net-web-api owin

我一直在查看ASP.NET身份验证附带的ASP.NET Web API默认项目,它使用Owin。我已经开始搜索它,并发现Owin旨在将应用程序与服务器分离,并且它的功能基于Startup类,它确实在项目中退出。该类被分成两个文件,就像那样

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}

public partial class Startup
{
    static Startup()
    {
        PublicClientId = "self";

        UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }

    public static string PublicClientId { get; private set; }

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // 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
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

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

然而,名称空间上方的第一个文件有这一行

[assembly: OwinStartup(typeof(WebApplication1.Startup))]

现在这个类只用在auth控制器上,但基本上它只用于构建用户管理器并获取OAuthOptions.AccessTokenFormatPublicClientId信息。

在该设置中,该类仅用于提供这些信息。那么,这堂课真正发挥作用呢?我真的不理解Owin和这个类之间的关系,它显然只是提供配置信息。

1 个答案:

答案 0 :(得分:6)

您需要将组件添加到Owin应用程序管道中以处理HTTP请求,否则不会发生任何事情:(

Owin使用Convention over configuration的软件设计原则来假设您的项目有一个名为Startup的类,其方法名为Configuration,它接受​​{{1}类型的一个参数这将把组件添加到Owin应用程序管道中。这背后的目的是让程序员更快更容易地设置,以便您可以花更多的时间来创建API。

如果出于任何原因,您无法完全遵循IAppBuilder类约定,那么还有其他方法可以将Owin指向将组件添加到Owin应用程序管道中的代码。您已经确定了其中一种方法:OwinStartup属性。

Startup

您可以详细了解OWIN启动类的功能及其检测方式here