Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net OWIN WebApiConfig not being called

I created a blank project so I could create an angular application. Now I have all that in place, I decided that I want to add Web API to this project. I installed all the required packages and set up the WebApiConfig.cs file. Then I installed OWIN and created the OWIN Startup Class. When I run my project, the OWIN Startup Class is invoked properly, but the WebApiConfig is not.

In the past (pre-OWIN) using Global.asax was how you fired all your configuration classes, but because I am using OWIN the global.asax file is not needed and therefore I never created it.

Has someone come across this before and knows what I am doing wrong?

Update 1

I added a Global.asax page and it executed. I was under the impression that if you use OWIN, you should delete your Global.asax file?

Here are both the Global.asax file

public class Global : HttpApplication
{

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

and the Startup.Config file.

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

Update 2

My startup class looks like this now:

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

If I uncomment the WebApiConfig line then the startup class is never executed. Any idea why?

like image 380
r3plica Avatar asked Mar 24 '15 11:03

r3plica


2 Answers

You'll need to call app.UseWebApi in your startup class, passing in the configuration you want to use. You'll also need to call your WebApiConfig's Register method there too. An example of how this might look in a cut down application is:

You could have an OWIN startup class that looks something like this:

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

The HttpConfiguration is created and passed to the WebApiConfig.Register method. We then use the app.UseWebApi(config) method to setup the web api. This is a helper method in System.Web.Http.Owin, you can get it by including the NuGet package Microsoft ASP.NET Web API 2.2 OWIN

The WebApiConfig class would look something like this:

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 }
            );
        }
    }
}
like image 85
Neil Mountford Avatar answered Oct 15 '22 06:10

Neil Mountford


Certainly, If you use Owin you may delete you Global.asax file.

In your Owin Startup.cs you have to put your WebApiConfig registration.

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

        HttpConfiguration config = new HttpConfiguration();

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

        ...

    }
...
}
like image 22
Xavier Egea Avatar answered Oct 15 '22 06:10

Xavier Egea