### Configure Startup Class for Welcome Page Source: https://github.com/aspnet/aspnetkatana/wiki/Hello-World Use this in your Startup.cs file to enable a simple welcome page when the application starts. Ensure you have `using Owin;`. ```csharp public void Configuration(IAppBuilder app) { app.UseWelcomePage(); } ``` -------------------------------- ### Get OwinHost Help Source: https://github.com/aspnet/aspnetkatana/blob/main/src/OwinHost/Package/ReadMe.md Display the full list of available command-line parameters for OwinHost.exe. ```bash OwinHost.exe /? ``` -------------------------------- ### Self-host an OWIN application with WebApp.Start Source: https://context7.com/aspnet/aspnetkatana/llms.txt Launch an OWIN application in any process using WebApp.Start. Dispose the returned IDisposable to shut down the server. Ensure the Microsoft.Owin.SelfHost NuGet package is installed. ```csharp using Microsoft.Owin.Hosting; using Owin; // Minimal self-host console application // NuGet: Microsoft.Owin.SelfHost class Program { static void Main() { var options = new StartOptions(); options.Urls.Add("http://localhost:9000"); options.Urls.Add("http://localhost:9001"); using (WebApp.Start(options, app => { app.Run(async ctx => { ctx.Response.ContentType = "application/json"; await ctx.Response.WriteAsync("{\"status\":\"ok\"}"); }); })) { Console.WriteLine("Listening on :9000 and :9001 — press Enter to quit"); Console.ReadLine(); } } } // With a typed Startup class using (WebApp.Start("http://localhost:9000")) { Console.ReadLine(); } ``` -------------------------------- ### Configure Cookie Authentication Middleware Source: https://context7.com/aspnet/aspnetkatana/llms.txt Configure the CookieAuthenticationOptions to define the authentication type, cookie settings, and paths for login and logout. This setup enables forms-authentication-style cookie sign-in and sign-out. ```csharp using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security; using System.Security.Claims; public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ApplicationCookie", CookieName = ".MyApp.Auth", LoginPath = new PathString("/account/login"), LogoutPath = new PathString("/account/logout"), ExpireTimeSpan = TimeSpan.FromHours(8), SlidingExpiration = true, CookieHttpOnly = true, CookieSecure = CookieSecureOption.SameAsRequest, CookieSameSite = SameSiteMode.Lax, ReturnUrlParameter = "returnUrl" }); // Sign in a user (from a login handler) app.Run(async ctx => { if (ctx.Request.Path == "/account/login" && ctx.Request.Method == "POST") { var identity = new ClaimsIdentity("ApplicationCookie"); identity.AddClaim(new Claim(ClaimTypes.Name, "alice")); identity.AddClaim(new Claim(ClaimTypes.Role, "admin")); ctx.Authentication.SignIn( new AuthenticationProperties { IsPersistent = true }, identity); ctx.Response.Redirect("/dashboard"); return; } if (ctx.Request.Path == "/account/logout") { ctx.Authentication.SignOut("ApplicationCookie"); ctx.Response.Redirect("/"); return; } await ctx.Response.WriteAsync("Hello " + ctx.Request.User?.Identity?.Name); }); } ``` -------------------------------- ### Configure host binding and startup with StartOptions Source: https://context7.com/aspnet/aspnetkatana/llms.txt Control URL binding, startup class loading, and server factory using StartOptions. Settings can be passed via the Settings dictionary. ```csharp using Microsoft.Owin.Hosting; var options = new StartOptions { // Explicit startup class (overrides auto-detection) AppStartup = "MyApp.ProductionStartup, MyApp", // Server implementation assembly ServerFactory = "Microsoft.Owin.Host.HttpListener", // Port shorthand (alternative to Urls) Port = 8080 }; options.Urls.Add("http://+:443"); // listen on all interfaces options.Settings["traceoutput"] = "true"; // optional settings bag using (WebApp.Start(options)) { Console.ReadLine(); } ``` -------------------------------- ### Configure Katana Startup in Web.Config Source: https://github.com/aspnet/aspnetkatana/wiki/Configuration Use these settings in your Web.Config file to specify the startup class and control automatic startup detection for Katana applications. `owin:appStartup` defines the entry point, while `owin:AutomaticAppStartup` enables or disables the OwinHttpModule. ```xml ``` -------------------------------- ### Self-host OWIN Application Source: https://github.com/aspnet/aspnetkatana/blob/main/src/Microsoft.Owin.SelfHost/README.md Use WebApp.Start to host an OWIN application. The Startup class is called to configure the application pipeline. ```csharp using (WebApp.Start("http://localhost:12345")) { Console.ReadLine(); } public class Startup { public void Configuration(IAppBuilder app) { #if DEBUG app.UseErrorPage(); #endif app.UseWelcomePage("/"); } } ``` -------------------------------- ### Launch OwinHost with a Custom Server Source: https://github.com/aspnet/aspnetkatana/blob/main/src/OwinHost/Package/ReadMe.md Specify an alternate OWIN-compatible server assembly to be used by OwinHost.exe. ```bash OwinHost.exe -s ``` -------------------------------- ### Web.config AppSettings for Katana Configuration Source: https://context7.com/aspnet/aspnetkatana/llms.txt Use these settings in Web.config to control Katana's startup behavior. The 'owin:appStartup' key specifies the startup class, while 'owin:AutomaticAppStartup' can disable automatic discovery. ```xml ``` -------------------------------- ### Create and Use TestServer with HttpClient Source: https://github.com/aspnet/aspnetkatana/blob/main/src/Microsoft.Owin.Testing/ReadMe.txt Creates a TestServer, adds middleware to the OWIN pipeline, and submits a request using HttpClient. Ensure to dispose of the TestServer after use. ```csharp using(var server = TestServer.Create(app => { app.UseErrorPage(); // See Microsoft.Owin.Diagnostics app.Run(context => { return context.Response.WriteAsync("Hello world using OWIN TestServer"); }); })) { HttpResponseMessage response = await server.HttpClient.GetAsync("/"); // TODO: Validate response } ``` -------------------------------- ### Run Katana App from Console Application Source: https://github.com/aspnet/aspnetkatana/wiki/Hello-World This code snippet demonstrates how to self-host a Katana application from a console application. It requires the `Microsoft.Owin.Hosting` namespace and a `Startup` class. ```csharp using (WebApp.Start("http://localhost:12345")) { Console.WriteLine("Listening on http://localhost:12345"); Console.ReadLine(); } ``` -------------------------------- ### Multiple Named Startup Classes with OwinStartup Attribute Source: https://context7.com/aspnet/aspnetkatana/llms.txt Define multiple named startup classes using the OwinStartup attribute in C#. These can then be selected via the 'owin:appStartup' key in Web.config. ```csharp // Multiple named startup classes selected via web.config [assembly: OwinStartup("Production", typeof(MyApp.ProductionStartup))] [assembly: OwinStartup("Staging", typeof(MyApp.StagingStartup))] // In Web.config: ``` -------------------------------- ### Serve Static Files with UseStaticFiles Source: https://context7.com/aspnet/aspnetkatana/llms.txt Use UseStaticFiles to serve files from the file system with ETag and conditional request support. Configure request path, file system, and response headers like Cache-Control. ```csharp using Microsoft.Owin.StaticFiles; using Microsoft.Owin.FileSystems; public void Configuration(IAppBuilder app) { // Serve files from /wwwroot mapped to URL path / app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString("/static"), FileSystem = new PhysicalFileSystem(@".\wwwroot"), ServeUnknownFileTypes = false, OnPrepareResponse = ctx => { // Add cache headers to every file response ctx.OwinContext.Response.Headers["Cache-Control"] = "public,max-age=86400"; } }); // All-in-one: default files + directory browsing + static files app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/files"), FileSystem = new PhysicalFileSystem(@"C:\\shared"), EnableDirectoryBrowsing = true, EnableDefaultFiles = true, // serves index.html automatically DefaultFilesOptions = { DefaultFileNames = { "index.html", "default.html" } } }); } ``` -------------------------------- ### Create and Use TestServer with CreateRequest Source: https://github.com/aspnet/aspnetkatana/blob/main/src/Microsoft.Owin.Testing/ReadMe.txt Submits a request to the TestServer using the CreateRequest helper method, allowing for custom headers. Ensure to dispose of the TestServer after use. ```csharp HttpResponseMessage response = await server.CreateRequest("/") .AddHeader("header1", "headervalue1") .GetAsync(); ``` -------------------------------- ### Configure Katana Trace Logging to File Source: https://github.com/aspnet/aspnetkatana/wiki/Debugging Direct Katana's .NET trace logs to a file for easier debugging. Ensure the 'Microsoft.Owin' source is enabled with 'Verbose' level. ```xml ``` -------------------------------- ### Register typed middleware with AppBuilder.Use Source: https://context7.com/aspnet/aspnetkatana/llms.txt Insert a class-based middleware into the pipeline using Use. The middleware class must have a constructor accepting the next AppFunc and an Invoke method. ```csharp // Custom middleware class public class LoggingMiddleware { private readonly Func, Task> _next; public LoggingMiddleware(Func, Task> next) { _next = next; } public async Task Invoke(IDictionary environment) { var context = new OwinContext(environment); Console.WriteLine($"[IN] {context.Request.Method} {context.Request.Path}"); await _next(environment); Console.WriteLine($"[OUT] {context.Response.StatusCode}"); } } // Registration public void Configuration(IAppBuilder app) { app.Use(); app.Run(ctx => ctx.Response.WriteAsync("Done")); } ``` -------------------------------- ### Enable All Managed Modules in IIS Source: https://github.com/aspnet/aspnetkatana/wiki/Static-Files-on-IIS Add this to your web.config to ensure IIS does not skip managed Asp.Net modules when the native static file module finds a match. ```xml ``` -------------------------------- ### Compose an OWIN pipeline with IAppBuilder Source: https://context7.com/aspnet/aspnetkatana/llms.txt Register inline middleware with next-forwarding and a terminal handler using IAppBuilder. Ensure necessary using directives are present. ```csharp using Owin; using Microsoft.Owin; using System.Threading.Tasks; public class Startup { public void Configuration(IAppBuilder app) { // 1. Inline middleware with next-forwarding app.Use(async (context, next) => { context.Response.Headers["X-Request-Id"] = Guid.NewGuid().ToString(); await next(); // call the next component }); // 2. Terminal handler — does not call next app.Run(async context => { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello, OWIN!"); }); } } ``` -------------------------------- ### Configure Diagnostics Middleware with UseErrorPage and UseWelcomePage Source: https://context7.com/aspnet/aspnetkatana/llms.txt Use diagnostics middleware for developer-friendly error pages and a welcome page. UseErrorPage provides detailed error information based on the application mode, while UseWelcomePage offers a simple health check page. ```csharp using Owin; public void Configuration(IAppBuilder app) { // Rich error page — only shows full details when host.AppMode == "development" app.UseErrorPage(new Microsoft.Owin.Diagnostics.ErrorPageOptions { ShowExceptionDetails = true, ShowHeaders = true, ShowEnvironment = true, ShowCookies = true, SourceCodeLineCount = 10 }); // Simple "it works" welcome page at a specific path app.UseWelcomePage("/health"); // Deliberately throw to verify error page app.Run(ctx => { throw new InvalidOperationException("Test error"); }); } ``` -------------------------------- ### Inspect and Modify OWIN Request/Response Source: https://context7.com/aspnet/aspnetkatana/llms.txt Use IOwinContext, IOwinRequest, and IOwinResponse to access request details like method, path, headers, and cookies. Construct responses by setting status codes, content types, headers, and writing content. This middleware handles the entire request lifecycle without calling the next middleware. ```csharp app.Use(async (IOwinContext ctx, Func next) => { // --- Request inspection --- string method = ctx.Request.Method; // "GET" PathString path = ctx.Request.Path; // PathString("/api/users") string query = ctx.Request.QueryString.Value; // "page=2&size=10" string ip = ctx.Request.RemoteIpAddress; bool isHttps = ctx.Request.IsSecure; string authHdr = ctx.Request.Headers["Authorization"]; // Read posted form IFormCollection form = await ctx.Request.ReadFormAsync(); string username = form["username"]; // Read a cookie string token = ctx.Request.Cookies["session"]; // --- Response construction --- ctx.Response.StatusCode = 200; ctx.Response.ContentType = "application/json"; ctx.Response.Headers["Cache-Control"] = "no-store"; ctx.Response.Cookies.Append("session", "abc123", new CookieOptions { HttpOnly = true, Secure = true, Expires = DateTimeOffset.UtcNow.AddHours(1) }); await ctx.Response.WriteAsync("{\"user\":\"alice\"}"); // Don't call next — request is fully handled }); ``` -------------------------------- ### Add Stage Marker for Static File Middleware Source: https://github.com/aspnet/aspnetkatana/wiki/Static-Files-on-IIS Append this Owin middleware to your pipeline after the static file middleware to ensure it runs correctly within the IIS integrated pipeline. ```csharp app.UseStageMarker(PipelineStage.MapHandler); ``` -------------------------------- ### Configure OAuth 2.0 Authorization Server Source: https://context7.com/aspnet/aspnetkatana/llms.txt Configures the OWIN pipeline to act as an OAuth 2.0 authorization server. Supports token and authorize endpoints with configurable providers for client authentication and resource owner credentials. ```csharp using Microsoft.Owin.Security.OAuth; using System.Security.Claims; public void Configuration(IAppBuilder app) { app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/oauth/token"), AuthorizeEndpointPath = new PathString("/oauth/authorize"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(1), AllowInsecureHttp = true, // dev only Provider = new OAuthAuthorizationServerProvider { // Validate client credentials (client_id / client_secret) OnValidateClientAuthentication = context => { string clientId, clientSecret; if (context.TryGetBasicCredentials(out clientId, out clientSecret) && clientId == "my-app" && clientSecret == "secret") { context.Validated(); } return Task.CompletedTask; }, // Resource owner password grant OnGrantResourceOwnerCredentials = async context => { if (context.UserName == "alice" && context.Password == "pass") { var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, "user")); context.Validated(identity); } }, // Client credentials grant OnGrantClientCredentials = context => { var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("client_id", context.ClientId)); context.Validated(identity); return Task.CompletedTask; } } }); // Token request example: // POST /oauth/token // grant_type=password&username=alice&password=pass&client_id=my-app&client_secret=secret // → { "access_token": "...", "token_type": "bearer", "expires_in": 3600 } } ``` -------------------------------- ### Configure Static File Middleware with Custom Path Source: https://github.com/aspnet/aspnetkatana/wiki/Static-Files-on-IIS Use this alternative approach to configure the static file middleware with a specific request path, bypassing the native IIS static file module's URL matching. ```csharp app.UseFileServer(new FileServerOptions { FileSystem = new PhysicalFileSystem(".\\public"), RequestPath = new PathString("/files"), }); ``` -------------------------------- ### Reconfigure CookieAuthenticationMiddleware with SystemWebCookieManager Source: https://github.com/aspnet/aspnetkatana/wiki/System.Web-response-cookie-integration-issues Configure the CookieAuthenticationMiddleware to use SystemWebCookieManager for writing cookies directly to System.Web's cookie collection. This is a workaround for conflicts between OWIN and System.Web cookie handling. ```csharp app.UseCookieAuthentication(new CookieAuthenticationOptions { // ... CookieManager = new SystemWebCookieManager() }); ``` -------------------------------- ### In-Memory Integration Testing with TestServer Source: https://context7.com/aspnet/aspnetkatana/llms.txt TestServer hosts the OWIN pipeline in memory, providing an HttpClient for sending test requests without network involvement. It's useful for integration testing of your OWIN application. ```csharp using Microsoft.Owin.Testing; using System.Net.Http; using Xunit; public class ApiTests { [Fact] public async Task GetReturns200() { using (var server = TestServer.Create(app => { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Test" }); app.Run(async ctx => { if (ctx.Request.Path == "/ping") { ctx.Response.ContentType = "text/plain"; await ctx.Response.WriteAsync("pong"); return; } ctx.Response.StatusCode = 404; }); })) { HttpClient client = server.HttpClient; HttpResponseMessage response = await client.GetAsync("/ping"); Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); string body = await response.Content.ReadAsStringAsync(); Assert.Equal("pong", body); } } [Fact] public async Task CustomHeaderIsPresent() { using (var server = TestServer.Create()) { // Use RequestBuilder for fine-grained request construction var response = await server.CreateRequest("/api/data") .AddHeader("Authorization", "Bearer test-token") .GetAsync(); Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); } } } ``` -------------------------------- ### Configure CORS Policy Source: https://context7.com/aspnet/aspnetkatana/llms.txt Configures OWIN to handle Cross-Origin Resource Sharing (CORS) requests. Supports allowing all origins or defining fine-grained policies with specific origins, headers, and methods. ```csharp using Microsoft.Owin.Cors; using System.Web.Cors; using System.Threading.Tasks; public void Configuration(IAppBuilder app) { // Allow everything (development / public API) app.UseCors(CorsOptions.AllowAll); // Fine-grained policy app.UseCors(new CorsOptions { PolicyProvider = new CorsPolicyProvider { PolicyResolver = request => { var policy = new CorsPolicy { AllowAnyHeader = true, AllowAnyMethod = true, SupportsCredentials = true }; // Only allow specific origins policy.Origins.Add("https://app.example.com"); policy.Origins.Add("https://admin.example.com"); return Task.FromResult(policy); } } }); app.Run(ctx => ctx.Response.WriteAsync("CORS-enabled response")); } ``` -------------------------------- ### Configure Bearer Token Authentication Source: https://context7.com/aspnet/aspnetkatana/llms.txt Configures OWIN to validate incoming Bearer tokens from the Authorization header. It can optionally extract tokens from query parameters and adds the token's claims to the authenticated principal. ```csharp using Microsoft.Owin.Security.OAuth; public void Configuration(IAppBuilder app) { // Must share the same token format/provider as the authorization server app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { // Optionally override how the token is extracted Provider = new OAuthBearerAuthenticationProvider { OnRequestToken = context => { // Also accept token from query string (e.g. SignalR) var token = context.Request.Query["access_token"]; if (!string.IsNullOrEmpty(token)) context.Token = token; return Task.CompletedTask; } } }); app.Run(async ctx => { if (!ctx.Request.User.Identity.IsAuthenticated) { ctx.Response.StatusCode = 401; await ctx.Response.WriteAsync("Unauthorized"); return; } var name = ctx.Request.User.Identity.Name; await ctx.Response.WriteAsync($"Hello, {name}"); }); } ``` -------------------------------- ### Control Pipeline Stage with UseStageMarker Source: https://context7.com/aspnet/aspnetkatana/llms.txt UseStageMarker controls the execution stage of OWIN middleware within the IIS integrated pipeline. This allows middleware to run before or after native IIS modules by specifying the desired PipelineStage. ```csharp using Microsoft.Owin.Extensions; public void Configuration(IAppBuilder app) { // Authentication middleware runs at the Authenticate stage app.UseCookieAuthentication(new CookieAuthenticationOptions { ... }); app.UseStageMarker(PipelineStage.Authenticate); // Route-level middleware runs later app.Use(async (ctx, next) => { await next(); }); app.UseStageMarker(PipelineStage.ResolveCache); // Available stages (in order): // Authenticate, PostAuthenticate, Authorize, PostAuthorize, // ResolveCache, PostResolveCache, MapHandler, PostMapHandler, // AcquireState, PostAcquireState, PreHandlerExecute } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.