.Net OWIN WebApiConfig没有被调用

时间:2015-03-24 11:24:22

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

我创建了一个空白项目,因此我可以创建一个角度应用程序。 现在我已经完成了所有这些工作,我决定将Web API添加到此项目中。我安装了所有必需的软件包并设置了 WebApiConfig.cs 文件。 然后我安装了 OWIN 并创建了 OWIN启动类。当我运行我的项目时, OWIN启动类被正确调用,但 WebApiConfig 不是。

过去(OWIN之前)使用 Global.asax 是你解雇所有配置类的方法,但因为我使用 OWIN 全局。不需要asax 文件,因此我从未创建过它。

有人之前遇到过这个并且知道我做错了吗?

更新1

我添加了 Global.asax 页面并执行了该页面。 我的印象是,如果您使用 OWIN ,则应删除 Global.asax 文件?

以下是 Global.asax 文件

public class Global : HttpApplication
{

    protected void Application_Start()
    {
        // Add these two lines to initialize Routes and Filters:
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }
}

Startup.Config 文件。

public class StartupConfig
{
    public static UserService<User> UserService { get; set; }
    public static string PublicClientId { get; private set; }
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    static StartupConfig()
    {
        UserService = new UserService<User>(new UnitOfWork<DatabaseContext>(), false, true);
        PublicClientId = "self";

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

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void Configuration(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: "vnaJZLYwWFbv7GBlDeMbfwAlD",
        //    consumerSecret: "Q1FE1hEN6prXnK2O9TYihTFyOQmcQmrZJses0rT8Au4OsDQISQ");

        //app.UseFacebookAuthentication(
        //    appId: "",
        //    appSecret: "");

        //app.UseGoogleAuthentication();
    }
}

更新2

我的启动课现在看起来像这样:

public class StartupConfig
{
    public static UserService<User> UserService { get; set; }
    public static string PublicClientId { get; private set; }
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    static StartupConfig()
    {
        UserService = new UserService<User>(new UnitOfWork<DatabaseContext>(), false, true);
        PublicClientId = "self";

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

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void Configuration(IAppBuilder app)
    {
        //var config = new HttpConfiguration();

        //// Set up our configuration
        //WebApiConfig.Register(config);

        // 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: "vnaJZLYwWFbv7GBlDeMbfwAlD",
        //    consumerSecret: "Q1FE1hEN6prXnK2O9TYihTFyOQmcQmrZJses0rT8Au4OsDQISQ");

        //app.UseFacebookAuthentication(
        //    appId: "",
        //    appSecret: "");

        //app.UseGoogleAuthentication();
    }
}

如果我取消注释WebApiConfig行,则永远不会执行启动类。 知道为什么吗?

2 个答案:

答案 0 :(得分:6)

您需要在启动类中调用app.UseWebApi,并传入您要使用的配置。您还需要在那里调用WebApiConfig的Register方法。在减少的应用程序中,这可能是一个例子:

你可以有一个看起来像这样的OWIN启动类:

// Tell OWIN to start with this
[assembly: OwinStartup(typeof(MyWebApi.Startup))]
namespace MyWebApi
{
    public class Startup
    {
        /// <summary>
        /// This method gets called automatically by OWIN when the application starts, it will pass in the IAppBuilder instance.
        /// The WebApi is registered here and one of the built in shortcuts for using the WebApi is called to initialise it.
        /// </summary>
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
    }
}

创建HttpConfiguration并将其传递给WebApiConfig.Register方法。然后,我们使用app.UseWebApi(config)方法设置web api。这是System.Web.Http.Owin中的辅助方法,您可以通过包含NuGet包Microsoft ASP.NET Web API 2.2 OWIN

来获取它

WebApiConfig类看起来像这样:

namespace MyWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

答案 1 :(得分:1)

当然,如果您使用Owin,您可能会删除Global.asax文件。

在你的Owin Startup.cs中,你必须进行WebApiConfig注册。

public class Startup 
{
    public void Configuration(IAppBuilder app)
    {
        ...

        HttpConfiguration config = new HttpConfiguration();

        WebApiConfig.Register(config);
        config.Filters.Add(new WebApiAuthorizeAttribute());

        ...

    }
...
}