public void Configuration(IAppBuilder app) { var db = new ApplicationDbContext(); var userManager = new UserManager<User, int>(new UserStore(db)); var roleManager = new RoleManager<UserRole, int>(new RoleStore(db)); var sb = new StringBuilder(); var format = "{0, -3} | {1, -15} | {2, -30} | {3, -20}"; sb.AppendLine("ASP.NET Identity Users:\n"); sb.AppendLine(string.Format(format, "ID", "Username", "Email", "Role(s)")); sb.AppendLine("-----------------------------------------------------------------------------"); foreach (var user in userManager.Users.Include(u => u.Roles)) { sb.AppendLine(string.Format(format, user.Id, user.UserName, user.Email, string.Join(", ", user.Roles.Select(r => r.Name).ToArray()))); } sb.AppendLine("\n\nASP.NET Identity Roles:\n"); format = "{0, -3} | {1, -20}"; sb.AppendLine(string.Format(format, "ID", "Role")); sb.AppendLine("--------------------------"); foreach (var role in roleManager.Roles) { sb.AppendLine(string.Format(format, role.Id, role.Name)); } app.Run(context => { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync(sb.ToString()); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { if (context.Request.Method == "POST" && context.Request.Uri.OriginalString.EndsWith("/test")) { context.Response.StatusCode = 302; return context.Response.WriteAsync("Found!"); } if (context.Request.Method == "POST" && context.Request.Uri.OriginalString.EndsWith("/json")) { context.Response.ContentType = "application/json"; return context.Response.WriteAsync("{\"IntegerValue\":1,\"StringValue\":\"Test\"}"); } if (context.Request.Method == "POST" && context.Request.Uri.OriginalString.EndsWith("/nomodel")) { context.Response.ContentType = "application/json"; return context.Response.WriteAsync("{\"id\":1}"); } if (context.Request.Headers.ContainsKey("CustomHeader")) { return context.Response.WriteAsync("OK!"); } context.Response.StatusCode = 404; return context.Response.WriteAsync("Not found!"); }); }
public void WaadAuthenticationWithProviderConfiguration(IAppBuilder app) { app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters() { ValidAudience = "http://localhost/redirectUri" }, Tenant = "4afbc689-805b-48cf-a24c-d4aa3248a248", BackchannelCertificateValidator = new WaadCertificateValidator(), BackchannelHttpHandler = new WaadChannelHttpHandler(), }); app.Run(async context => { if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated) { context.Authentication.Challenge("Bearer"); await context.Response.WriteAsync("Unauthorized"); } else { if (!context.Get<bool>("OnRequestToken") || !context.Get<bool>("OnValidateIdentity")) { await context.Response.WriteAsync("Provider not invoked"); } else { await context.Response.WriteAsync("Bearer"); } } }); }
public void Configuration(IAppBuilder app) { app.Run(context => { var name = context.Request.Query.Get("name"); var x = int.Parse(context.Request.Query.Get("x")); var y = int.Parse(context.Request.Query.Get("y")); var e = Enum.Parse(typeof(MyEnum), context.Request.Query.Get("e")); var mc = new MyClass { Name = name, Sum = (x + y) * (int)e }; var json = JsonConvert.SerializeObject(mc); var enc = System.Text.Encoding.UTF8.GetBytes(json); context.Response.ContentType = "application/json"; // sync write or async write if (context.Request.Query.Get("sync") == "true") { context.Response.Body.Write(enc, 0, enc.Length); return EmptyTask; // Task.FromResult<object>(null) } else { return context.Response.Body.WriteAsync(enc, 0, enc.Length); } }); }
public void KnownStagesSpecified(IAppBuilder app) { app.UseErrorPage(); app.Use <BreadCrumbMiddleware>("a", "Authenticate"); AddStageMarker(app, "Authenticate"); app.Use <BreadCrumbMiddleware>("b", "PostAuthenticate"); AddStageMarker(app, "PostAuthenticate"); app.Use <BreadCrumbMiddleware>("c", "Authorize"); AddStageMarker(app, "Authorize"); app.Use <BreadCrumbMiddleware>("d", "PostAuthorize"); AddStageMarker(app, "PostAuthorize"); app.Use <BreadCrumbMiddleware>("e", "ResolveCache"); AddStageMarker(app, "ResolveCache"); app.Use <BreadCrumbMiddleware>("f", "PostResolveCache"); AddStageMarker(app, "PostResolveCache"); app.Use <BreadCrumbMiddleware>("g", "MapHandler"); AddStageMarker(app, "MapHandler"); app.Use <BreadCrumbMiddleware>("h", "PostMapHandler"); AddStageMarker(app, "PostMapHandler"); app.Use <BreadCrumbMiddleware>("i", "AcquireState"); AddStageMarker(app, "AcquireState"); app.Use <BreadCrumbMiddleware>("j", "PostAcquireState"); AddStageMarker(app, "PostAcquireState"); app.Use <BreadCrumbMiddleware>("k", "PreHandlerExecute"); AddStageMarker(app, "PreHandlerExecute"); app.Run(context => { var fullBreadCrumb = context.Get <string>("test.BreadCrumb"); Assert.Equal("abcdefghijk", fullBreadCrumb); return(Task.FromResult(0)); }); }
/// <summary> /// Adds a middleware to the OWIN pipeline that will be constructed using Autofac and that does not have next middleware /// </summary> /// <param name="app">The application builder.</param> /// <param name="handler">The handler to invoke. The constructed middleware will be available as a parameter.</param> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="app"/> or <paramref name="handler"/> is <see langword="null"/>. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if lifetime scope injector not registered in pipeline. /// </exception> /// <example> /// <code lang="C#"> /// app /// .UseAutofacLifetimeScopeInjector(container) /// .RunFromContainer<Uploader>((uploader, owinContext) => uploader.InvokeAsync(owinContext)); /// </code> /// </example> /// <seealso cref="AutofacAppBuilderExtensions.UseAutofacLifetimeScopeInjector(IAppBuilder, ILifetimeScope)"/> public static void RunFromContainer <T>(this IAppBuilder app, Func <T, IOwinContext, Task> handler) { if (app == null) { throw new ArgumentNullException("app"); } if (handler == null) { throw new ArgumentNullException("handler"); } if (!app.IsAutofacLifetimeScopeInjectorRegistered()) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Resources.LifetimeScopeInjectorNotFoundWhileRegisteringMiddleware, typeof(T))); } app .Run(context => { if (context == null) { throw new ArgumentNullException("context"); } return(handler(context.GetAutofacLifetimeScope().Resolve <T>(), context)); }); }
public void DefaultStaticFiles(IAppBuilder app) { app.Use((context, next) => { context.Response.Headers["PassedThroughOWIN"] = "True"; return(next()); }); app.UseStaticFiles(); app.Run(context => { context.Response.StatusCode = 402; return(context.Response.WriteAsync("Fell Through")); }); app.UseStageMarker(PipelineStage.MapHandler); }
public void CreateConfig(IAppBuilder appBuilder) { var config = GetSamlConfiguration(); appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "SAML2", AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active }); appBuilder.UseSamlAuthentication(new SamlAuthenticationOptions { Configuration = config, RedirectAfterLogin = "******" }); appBuilder.Run(async c => { if (c.Authentication.User?.Identity != null && c.Authentication.User.Identity.IsAuthenticated) { await c.Response.WriteAsync(c.Authentication.User.Identity.Name + "\r\n"); await c.Response.WriteAsync(c.Authentication.User.Identity.AuthenticationType + "\r\n"); foreach (var claim in c.Authentication.User.Identities.SelectMany(i => i.Claims)) { await c.Response.WriteAsync(claim.Value + "\r\n"); } await c.Response.WriteAsync("authenticated"); } else { c.Authentication.Challenge(c.Authentication.GetAuthenticationTypes().Select(d => d.AuthenticationType).ToArray()); } }); }
private static void ConfigureHttp(IAppBuilder app, string configFile, LogFactory requestLogging) { app.UseErrorPage(new ErrorPageOptions { ShowExceptionDetails = true }); app.Use(async(ctx, next) => { DecodeBody(ctx); await next(); }); app.Run(async ctx => { var config = ConfigJson.Deserialize <Configuration>(File.ReadAllText(configFile)); Http.Info("Incoming request {0} {1}", ctx.Request.Method, ctx.Request.Path); var responseSpec = config.FindMatching(ctx.Request.Method, ctx.Request.Path.ToString()) ?? new NotFoundResponse(); await responseSpec.Render(ctx.Request, ctx.Response, requestLogging); }); }
/// <summary> /// Configure owin application /// </summary> /// <param name="app">Owin application</param> public virtual void Configuration(IAppBuilder app) { // Initialize application var websiteRootDirectory = app.Properties.GetOrDefault <string>("host.WebsiteRootDirectory"); websiteRootDirectory = websiteRootDirectory ?? GetWebsiteRootDirectory(); Application.Ioc.RegisterMany <OwinWebsiteStopper>(); Application.Initialize(websiteRootDirectory); // Configure middlewares ConfigureMiddlewares(app); // Set request handler, it will running in thread pool // It can't throw any exception otherwise application will get killed app.Run(owinContext => Task.Run(() => { var context = new OwinHttpContextWrapper(owinContext); try { // Handle request Application.OnRequest(context); } catch (OwinHttpResponseEndException) { // Success } catch (Exception ex) { // Error try { Application.OnError(context, ex); } catch (OwinHttpResponseEndException) { // Handle error success } catch (Exception) { // Handle error failed } } })); }
public void Configuration(IAppBuilder app) { app.Run(context => { Stopwatch stopWatch = new Stopwatch(); Trace.WriteLine("Received client call. Starting stop watch now."); stopWatch.Start(); context.Request.CallCancelled.Register(() => { stopWatch.Stop(); Trace.WriteLine(string.Format("Cancellation token triggered. Elapsed time : {0}. Test should succeed", stopWatch.Elapsed)); NotificationServer.NotifyClient(); }); int retryCount = 0; while (retryCount < 3) { Thread.CurrentThread.Join(5 * 1000); if (context.Request.CallCancelled.IsCancellationRequested) { break; } retryCount++; } return(context.Response.WriteAsync("FAILURE")); }); }
public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); WebApiConfig.Register(config); StructureMapConfig.RegisterResolver(config); //TODO: make this more secure i.e. http://localhost:4200 var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*"); config.EnableCors(cors); var identityServerUrl = ConfigurationManager.AppSettings.Get("identityServerUrl"); app.UseIdentityServerBearerTokenAuthentication(new IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, Authority = identityServerUrl, RequiredScopes = new[] { "phonebookAPI.read", "phonebookAPI.write" } }); app.UseWebApi(config); app.Run(context => { context.Response.ContentType = "text/plain"; return(context.Response.WriteAsync("Hello, world.")); }); }
public async void Configuration(IAppBuilder app) { app.UseApplicationInsights(); var context = new OwinContext(app.Properties); var token = context.Get <CancellationToken>("host.OnAppDisposing"); app.Run(c => { if (c.Request.Path.ToString() == "/ping") { return(c.Response.WriteAsync("Pong", token)); } if (c.Request.Path.ToString() == "/version") { return(c.Response.WriteAsync(Assembly.GetExecutingAssembly().GetName().Version.ToString(), token)); } return(c.Response.WriteAsync("PassThePotato.Distributor Functional", token)); }); await ServiceBus.Startup(); if (token != CancellationToken.None) { token.Register(async() => { await ServiceBus.ShutdownBus(); }); } }
public void Configuration(IAppBuilder app) { app.Run(async context => { await context.Response.WriteAsync(Utility.GetWelcome()); }); }
public void CopyOfConfiguration(IAppBuilder app) { app.Run((context) => { return(context.Response.WriteAsync("CopyOfConfiguration")); }); }
public void CopyOfConfiguration(IAppBuilder app) { app.Run((context) => { return context.Response.WriteAsync("CopyOfConfiguration"); }); }
public void Configuration(IAppBuilder app) { if (!HasNoSecurityConfigured()) { Trace.TraceInformation("Using AAD middleware"); string audience = _configurationService.Get("ida.Audience"); string tenant = _configurationService.Get("ida.Tenant"); string aadInstance = _configurationService.Get("ida.AADInstance"); string metadataAddress = string.Format(aadInstance, tenant) + "/federationmetadata/2007-06/federationmetadata.xml"; app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true, ValidAudience = audience, ValidateIssuer = true, IssuerValidator = (string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return issuer; } }, Tenant = tenant, MetadataAddress = metadataAddress }); } Initialize(); app.Run(Invoke); }
public void Configuration(IAppBuilder app) { var configuration = new HttpConfiguration(); configuration.MapHttpAttributeRoutes(); configuration.EnsureInitialized(); configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings() { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; LinkyConfiguration.Configure(configuration); app.UseWebApi(configuration); app.UseDefaultFiles(new DefaultFilesOptions() { DefaultFileNames = new[] { "index.html" } }); app.UseFileServer(new FileServerOptions() { FileSystem = new PhysicalFileSystem(@".\content"), RequestPath = PathString.Empty, EnableDefaultFiles = true }); app.Run((context) => { var task = context.Response.WriteAsync("Hello world!"); return(task); }); }
public void Configuration(IAppBuilder app) { #if DEBUG app.UseErrorPage(); #endif app.UseWelcomePage(new Microsoft.Owin.Diagnostics.WelcomePageOptions() { Path = new PathString("/welcome") }); app.Run(context => { context.Response.ContentType = "text/html"; string output = string.Format( "<p>I'm running on {0} </p><p>From assembly {1}</p>", Environment.OSVersion, System.Reflection.Assembly.GetEntryAssembly().FullName ); return context.Response.WriteAsync(output); }); }
public void Configuration(IAppBuilder app) { var apiConfig = new HttpConfiguration(); apiConfig.MapHttpAttributeRoutes(); app.UseWebApi(apiConfig); var fileSystem = new PhysicalFileSystem("wwwroot"); var staticFilesConfig = new FileServerOptions { FileSystem = fileSystem }; staticFilesConfig.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" }; app.UseFileServer(staticFilesConfig); app.Run(async context => { context.Response.StatusCode = 404; await context.Response.WriteAsync("Resource not found!"); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { return(context.Response.WriteAsync("Startup.Configration")); }); }
/// <summary> /// 启动类的配置方法,格式是 Microsoft.Owin 所要求的 /// <para>必须是public,而且方法名和参数类型、参数数量都固定</para> /// </summary> /// <param name="builder">App生成器</param> public void Configuration(IAppBuilder builder) { //websocket中间件 builder.UseWebSocket(); //预处理中间件,放在第一位 builder.UseJwsIntegration(); // 添加FastWebApi中间件,具体实现,在WebApiMiddleware.cs文件中 /////////////////////////////////////////////////////////////////////////// builder.UseFastWebApi(new MyWebApiRouter()); // 放在处理链中最后执行的方法(相当于前一个中间件的next对象的Invoke方法) // 如果前边的中件间成功处理了请求,工作就不会交到这个位置来。 //////////////////////////////////////////////////////////////////////////// builder.Run((c) => { // 能流传到这儿,表示前边的中件没有处理 // 所以,应该返回找不到网页的信息(404) c.Response.StatusCode = 404; c.Response.Write(Encoding.ASCII.GetBytes(string.Format("Can't found The Path: {0}", c.Request.Path))); return(Task.FromResult(0)); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { return(context.Response.WriteAsync(RESULT)); }); }
public void Configuration(IAppBuilder app) { app.Run(async context => { if (context.Request.Method == "POST" && context.Request.Path.Value == "/start") { Console.WriteLine("Start..."); } else if (context.Request.Method == "GET" && context.Request.Path.Value == "/move") { var random = new Random(); var moves = new string[] { "ROCK", "PAPER", "SCISSORS" }; var move = moves[random.Next(0, moves.Length)]; context.Response.ContentType = "text/plain"; Console.WriteLine("myMove: " + move); await context.Response.WriteAsync(move); } else if (context.Request.Method == "POST" && context.Request.Path.Value == "/move") { var formData = await context.Request.ReadFormAsync(); var lastOpponentMove = formData.FirstOrDefault(x => x.Key == "lastOpponentMove").Value[0]; Console.WriteLine("lastOpponentMove: " + lastOpponentMove); } context.Response.StatusCode = 404; }); }
public void Configuration(IAppBuilder appBuilder) { var config = GetSamlConfiguration(); #if TEST config = TestEnvironmentConfiguration(); #endif appBuilder.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions { AuthenticationType = "SAML2", AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active }); appBuilder.UseSamlAuthentication(new Owin.Security.Saml.SamlAuthenticationOptions { Configuration = config, RedirectAfterLogin = "******", }); appBuilder.Run(async c => { if (c.Authentication.User != null && c.Authentication.User.Identity != null && c.Authentication.User.Identity.IsAuthenticated) { await c.Response.WriteAsync(c.Authentication.User.Identity.Name + "\r\n"); await c.Response.WriteAsync(c.Authentication.User.Identity.AuthenticationType + "\r\n"); foreach (var claim in c.Authentication.User.Identities.SelectMany(i => i.Claims)) await c.Response.WriteAsync(claim.Value + "\r\n"); await c.Response.WriteAsync("authenticated"); } else { // trigger authentication c.Authentication.Challenge(c.Authentication.GetAuthenticationTypes().Select(d => d.AuthenticationType).ToArray()); } return; }); }
public void Configuration(IAppBuilder app) { app.UseWelcomePage(new PathString("/Welcome")); app.UseFileServer(new FileServerOptions { EnableDirectoryBrowsing = false, FileSystem = new PhysicalFileSystem(@"..\..\..\KatanaApp\StaticResources"), RequestPath = new PathString(@"/contents") }); app.Run(ctx => { if (string.IsNullOrEmpty(ctx.Request.Path.Value) || ctx.Request.Path.Value == "/" || ctx.Request.Path.Value == "/Welcome/") { ctx.Response.Redirect("/app/Welcome"); } // New code: Throw an exception for this URI path. if (ctx.Request.Path.Value == @"/fail") { throw new HttpException(500, "Random exception"); } ctx.Response.ContentType = "text/plain"; return ctx.Response.WriteAsync("Hello World!"); }); }
internal void WaadAuthenticationWithProviderConfiguration(IAppBuilder app) { app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters() { ValidAudience = "http://localhost/redirectUri" }, Tenant = "4afbc689-805b-48cf-a24c-d4aa3248a248", BackchannelCertificateValidator = new WaadCertificateValidator(), BackchannelHttpHandler = new WaadChannelHttpHandler(), }); app.Run(async context => { if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated) { context.Authentication.Challenge("Bearer"); await context.Response.WriteAsync("Unauthorized"); } else { if (!context.Get <bool>("OnRequestToken") || !context.Get <bool>("OnValidateIdentity")) { await context.Response.WriteAsync("Provider not invoked"); } else { await context.Response.WriteAsync("Bearer"); } } }); }
public void Configuration(IAppBuilder app) { app.MapSignalR<SamplePersistentConnection>("/SamplePC"); app.Run((context) => { if (context.Request.Path.Value.Equals("/", StringComparison. CurrentCultureIgnoreCase)) { context.Response.ContentType = "text/html"; string result = System.IO.File.ReadAllText(System.Environment. CurrentDirectory + "\\index.html"); return context.Response.WriteAsync(result); } if (context.Request.Path.Value.StartsWith("/scripts/", StringComparison. CurrentCultureIgnoreCase)) { context.Response.ContentType = "text/javascript"; //The requested should be verified but adding for simplicity of example. string result = System.IO.File.ReadAllText(System.Environment. CurrentDirectory + context.Request.Path.Value); return context.Response.WriteAsync(result); } return Task.FromResult<object>(null); }); }
public void Configuration(IAppBuilder builder) { builder.UseAlpha("a", "b"); builder.UseFunc(app => Alpha.Invoke(app, "a", "b")); builder.UseFunc(Alpha.Invoke, "a", "b"); builder.Use(Beta.Invoke("a", "b")); builder.UseFunc(Beta.Invoke, "a", "b"); builder.UseGamma("a", "b"); builder.Use(typeof(Gamma), "a", "b"); builder.UseType <Gamma>("a", "b"); builder.UseFunc <AppFunc>(app => new Gamma(app, "a", "b").Invoke); builder.Use(typeof(Delta), "a", "b"); builder.UseType <Delta>("a", "b"); builder.UseFunc <AppFunc>(app => new Delta(app, "a", "b").Invoke); builder.Run(this); }
public void Configuration(IAppBuilder app) { // Configure web api routing //var config = new HttpConfiguration(); //config.MapHttpAttributeRoutes(); //config.Routes.MapHttpRoute( // "DefaultApi", // "api/{controller}/{id}", // new { id = RouteParameter.Optional }); //app.UseWebApi(config); app.Run(ctx => { var file = ""; if (ctx.Request.Uri.AbsolutePath == "/Content/anduong.jpg") { ctx.Response.ContentType = "image/jpg"; ctx.Response.StatusCode = 200; file = ConfigurationManager.AppSettings["IMG_PATH"]; var buffer = File.ReadAllBytes(file); return(ctx.Response.WriteAsync(buffer)); } file = ConfigurationManager.AppSettings["HTML_PATH"]; var html = File.ReadAllText(file); ctx.Response.ContentType = "text/html"; return(ctx.Response.WriteAsync(html)); //return ctx.Response.WriteAsync("<!DOCTYPE html><html lang=\"en\"><head><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" /><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta name=\"safesai-verification\" content=\"SAFESAIdotCOMverification\" /><title>Trang chủ</title><meta name=\"description\" content=\"mo ta\" /><meta name=\"keywords\" content=\"Keywords\" /><meta property=\"og:site_name\" content=\"Trang tin F88\"><meta property=\"og:url\" content=\"https://test-web.f88.vn\" /><meta property=\"og:type\" content=\"article\" /><meta property=\"og:description\" content=\"Mô tả\"><meta property=\"og:image\" content=\"Content/anduong.jpg\"><meta property=\"og:image:secure_url\" content=\"Content/anduong.jpg\"><meta property=\"og:image:type\" content=\"image/jpg\"></head><body><h1>TEST FACEBOOK THUMBNAIL</h1> <img src=\"/Content/anduong.jpg\"></body></html>"); }); // Add welcome page //app.UseWelcomePage(); }
public void Configuration(IAppBuilder app) { app.Run(context => { context.Response.StatusCode = 404; var key = context.Request.Query["key"]; if (string.IsNullOrWhiteSpace(key)) { return(Task.CompletedTask); } var con = ConfigurationManager.ConnectionStrings[key]; if (con != null) { return(context.Response.WriteAsync($"{con.Name} {nameof(con.ConnectionString)}: {con.ConnectionString}, {nameof(con.ProviderName)}: {con.ProviderName}")); } var useLegend = DateTime.Now.Second % 2 == 1; var value = useLegend ? ConfigurationManager.AppSettings[key] : Global.Configuration[key]; if (value != null) { context.Response.StatusCode = 200; } context.Response.Headers["Content-Type"] = "text/html; charset=utf-8"; return(context.Response.WriteAsync((useLegend ? "ConfigurationManager: " : "Configuration: ") + (value ?? "undefined"))); }); }
public void Configuration(IAppBuilder app) { app.Use((ctx, next) => { var output = ctx.Get<TextWriter>("host.TraceOutput"); output.WriteLine("{0} {1}: {2}", ctx.Request.Scheme, ctx.Request.Method, ctx.Request.Path); return next(); }); GlobalHost.DependencyResolver.Register(typeof(VoteHub), () => new VoteHub(new QuestionRepository())); app.UseStaticFiles(); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); //app.MapSignalR(); app.Map("/signalr", map => map.UseCors(CorsOptions.Value) .RunSignalR(new HubConfiguration { EnableJSONP = true })); app.UseNancy(options => options.PerformPassThrough = context => context.Response.StatusCode == HttpStatusCode.NotFound); app.Run(context => { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync("Hello World!"); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { context.Response.ContentType = "text/html"; switch (context.Request.Path.Value) { case "/redirect": var x = context.Request.ReadFormAsync().Result; string clientId = x["clientid"]; string redirURL = HttpUtility.UrlEncode(x["redirect"]); string secret = x["secret"]; return context.Response.WriteAsync(string.Format("<a href='https://api.hubic.com/oauth/auth/?client_id={0}&redirect_uri={1}&scope=usage.r,account.r,getAllLinks.r,credentials.r,sponsorCode.r,activate.w,sponsored.r,links.drw&response_type=code&state=code'>Click here to authenticate</a>", clientId, redirURL)); case "/response/": if(context.Request.Query["error"] != null) { return context.Response.WriteAsync(string.Format("Error: {0} - {1}", context.Request.Query["error"], context.Request.Query["error_description"])); } else { return context.Response.WriteAsync("No errors!"); } default: return context.Response.WriteAsync(File.ReadAllText("startpage.html")); } }); }
public void Configuration(IAppBuilder builder) { builder.UseAlpha("a", "b"); builder.UseFunc(app => Alpha.Invoke(app, "a", "b")); builder.UseFunc(Alpha.Invoke, "a", "b"); builder.Use(Beta.Invoke("a", "b")); builder.UseFunc(Beta.Invoke, "a", "b"); builder.UseGamma("a", "b"); builder.Use(typeof(Gamma), "a", "b"); builder.UseType<Gamma>("a", "b"); builder.UseFunc<AppFunc>(app => new Gamma(app, "a", "b").Invoke); builder.Use(typeof(Delta), "a", "b"); builder.UseType<Delta>("a", "b"); builder.UseFunc<AppFunc>(app => new Delta(app, "a", "b").Invoke); builder.Run(this); }
/// <summary> /// 启动类的配置方法,其格式是 Microsoft.Owin.dll 约定的 /// <para>必须是public,而且方法名和参数类型、参数数量都固定</para> /// </summary> /// <param name="builder">App生成器</param> public void Configuration(IAppBuilder builder) { // 当一个请求到来时,运用自己的处理方法去处理 ////////////////////////////////////////////// builder.Run(MyHandler); //RUN方法之后,请不要再添加其它处理方法或“中间件” }
public void Configuration(IAppBuilder app) { //app.UseErrorPage(); //app.UseWelcomePage(); // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Formatters.Remove(config.Formatters.XmlFormatter); app.UseWebApi(config); app.Run(async (context) => // IOWinContext { context.Response.StatusCode = 200; context.Response.ContentType = "text/html"; string header = "<html><body><h1>Selfhost Vars</h1>"; await context.Response.WriteAsync(header); foreach (KeyValuePair<string, object> keyvalue in context.Environment) { if (keyvalue.Value == null) continue; string t = keyvalue.Key + ": " + keyvalue.Value.ToString() + "<hr />\r\n"; await context.Response.WriteAsync(t); //await Task.Delay(1000); // no output buffering - text just goes } await context.Response.WriteAsync("</body></html>"); }); }
public void Configuration (IAppBuilder app) { app.Use (typeof(MyMiddleWare)); app.Run (context => { return context.Response.WriteAsync("<h1>HelloWorld Dev</h1>"); }); }
public void Configuration(IAppBuilder app) { string audience = ConfigurationManager.AppSettings["ida:Audience"]; string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; if (!string.IsNullOrWhiteSpace(audience)) { string metadataAddress = string.Format(aadInstance, tenant) + "/federationmetadata/2007-06/federationmetadata.xml"; app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters { ValidAudience = audience, ValidateIssuer = true, IssuerValidator = (string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters) => { return issuer; } }, Tenant = tenant, MetadataAddress = metadataAddress }); } app.Run(Invoke); }
public void Configuration(IAppBuilder app) { app.Run(context => { return context.Response.WriteAsync("Startup.Configration"); }); }
public static void BuildSample(IAppBuilder app) { // add eventsource middleware app.EventSource(envKey); app.Run(context => { // get the event stream (not captured yet) var eventStream = context.Environment[envKey] as IEventStream; // create some timers to send mesages var timer = new System.Threading.Timer(_ => { var ts = DateTime.UtcNow.ToString("O"); eventStream.WriteAsync("Timer1:" + ts + message + "\n"); }, null, 1, 50); var timer2 = new System.Threading.Timer(_ => { var ts = DateTime.UtcNow.ToString("O"); eventStream.WriteAsync("Timer 2:" + ts + "\n"); }, null, 1, 25); // Capture the eventstream by calling Open and pass in the // clean-up logic for when this client closes the stream var task = eventStream.Open(() => { Console.WriteLine("Closed"); timer.Dispose(); timer2.Dispose(); }); eventStream.WriteAsync("Started\n"); return task; }); }
public void GoogleOAuth2Configuration(IAppBuilder app) { app.UseAuthSignInCookie(); var option = new GoogleOAuth2AuthenticationOptions() { ClientId = "581497791735.apps.googleusercontent.com", ClientSecret = "-N8rQkJ_MKbhpaxyjdVYbFpO", }; app.UseGoogleAuthentication(option); app.Run(async context => { if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated) { var authenticationProperties = new AuthenticationProperties(); authenticationProperties.Dictionary.Add("access_type", "custom_accessType"); authenticationProperties.Dictionary.Add("approval_prompt", "custom_approval_prompt"); authenticationProperties.Dictionary.Add("login_hint", "custom_login_hint"); context.Authentication.Challenge(authenticationProperties, "Google"); await context.Response.WriteAsync("Unauthorized"); } }); }
public void Configuration(IAppBuilder app) { app.Run(async context => { if (context.Request.Method != "GET") { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } await context.Response.WriteAsync(HtmlHeader); await context.Response.WriteAsync(ServerInfoHeader); await context.Response.WriteAsync(string.Format(" Local IP: {0}<br/>\n", context.Request.LocalIpAddress)); await context.Response.WriteAsync(string.Format(" Local Port: {0}<br/>\n", context.Request.LocalPort)); await context.Response.WriteAsync(string.Format(" Remote IP: {0}<br/>\n", context.Request.RemoteIpAddress)); await context.Response.WriteAsync(string.Format(" Remote Port: {0}<br/>\n", context.Request.RemotePort)); await context.Response.WriteAsync(ServerInfoFooter); await context.Response.WriteAsync(TableListHeader); foreach (var tableName in await GetTableNamesAsync()) { await context.Response.WriteAsync(string.Format(" <li>{0}</li>\n", tableName)); } await context.Response.WriteAsync(TableListFooter); await context.Response.WriteAsync(HtmlFooter); }); }
public void Configuration(IAppBuilder app) { var instrumentationKey = System.Configuration.ConfigurationManager.AppSettings.Get("Telemetry.InstrumentationKey"); if (!string.IsNullOrEmpty(instrumentationKey)) { // set it as early as possible to avoid losing telemetry TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey; } _searcherManager = CreateSearcherManager(); //test console app.Use(async (context, next) => { if (string.Equals(context.Request.Path.Value, "/console", StringComparison.OrdinalIgnoreCase)) { context.Response.Redirect(context.Request.PathBase + context.Request.Path + "/"); context.Response.StatusCode = 301; return; } else if (string.Equals(context.Request.Path.Value, "/console/", StringComparison.OrdinalIgnoreCase)) { context.Request.Path = new PathString("/console/Index.html"); } await next(); }); app.UseStaticFiles(new StaticFileOptions(new SharedOptions { RequestPath = new PathString("/console"), FileSystem = new EmbeddedResourceFileSystem(typeof(QueryMiddleware).Assembly, "NuGet.Services.Search.Console") })); app.Run(Invoke); }
public void Configuration(IAppBuilder app) { //Listando todo o pipeline app.Use(async (environment, next) => { foreach (var pair in environment.Environment) { Console.WriteLine("{0} : {1}", pair.Key, pair.Value); } await next(); }); //Exibindo o que foi requisitado e a resposta app.Use(async (environment, next) => { Console.WriteLine("Requisição: {0}", environment.Request.Path); await next(); Console.WriteLine("Resposta: {0}", environment.Response.StatusCode); }); app.Run(ctx => { return ctx.Response.WriteAsync("Fim!"); }); }
/// <summary> /// The Startup configuration sets up a pipeline with three middleware components, the first two displaying diagnostic information /// and the last one responding to events (and also displaying diagnostic information). The PrintCurrentIntegratedPipelineStage /// method displays the integrated pipeline event this middleware is invoked on and a message. /// </summary> public void Configuration(IAppBuilder app) { app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "Middleware 1"); return next.Invoke(); }); app.Use((context, next) => { PrintCurrentIntegratedPipelineStage(context, "2nd MW"); return next.Invoke(); }); // You can mark OMCs to execute at specific stages of the pipeline by using the IAppBuilder UseStageMarker() extension method. // To run a set of middleware components during a particular stage, insert a stage marker right after the last component is the set // during registration. There are rules on which stage of the pipeline you can execute middleware and the order components must run // (The rules are explained later in the tutorial). Add the UseStageMarker method to the Configuration code as shown below: app.UseStageMarker(PipelineStage.Authenticate); app.Run(context => { PrintCurrentIntegratedPipelineStage(context, "3rd MW"); return context.Response.WriteAsync("Hello world"); }); app.UseStageMarker(PipelineStage.ResolveCache); }
public void Configuration(IAppBuilder app) { // app.UseWelcomePage("/"); //app.Use(new Func<AppFunc, AppFunc>( // next => ( // env => // { // string strText = "原始方式的Owin"; // var response = env["owin.ResponseBody"] as Stream; // var responseHeaders = env["owin.ResponseHeader"] as Dictionary<string, string[]>; // responseHeaders.Add("content-type", "text-plain"); // return response.WriteAsync(Encoding.UTF8.GetBytes(strText), 0, strText.Length); // } // ))); app.Use<HelloWorldMiddleware>(); app.Use<NonebaseMiddleware>(); app.Use((context, next) => { TextWriter output = context.Get<TextWriter>("host.TraceOutput"); return next().ContinueWith(result => { output.WriteLine("Scheme {0} : Method {1} : Path {2} : MS {3}", context.Request.Scheme, context.Request.Method, context.Request.Path, getTime()); }); }); // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888 app.Run(context => { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync("Hello Owin from selfhost!"); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { return context.Response.WriteAsync(RESULT); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { Stopwatch stopWatch = new Stopwatch(); Trace.WriteLine("Received client call. Starting stop watch now."); stopWatch.Start(); context.Request.CallCancelled.Register(() => { stopWatch.Stop(); Trace.WriteLine(string.Format("Cancellation token triggered. Elapsed time : {0}. Test should succeed", stopWatch.Elapsed)); NotificationServer.NotifyClient(); }); int retryCount = 0; while (retryCount < 3) { Thread.CurrentThread.Join(5 * 1000); if (context.Request.CallCancelled.IsCancellationRequested) { break; } retryCount++; } return context.Response.WriteAsync("FAILURE"); }); }
public void DefaultStaticFiles(IAppBuilder app) { app.Use((context, next) => { context.Response.Headers["PassedThroughOWIN"] = "True"; return next(); }); app.UseStaticFiles(); app.Run(context => { context.Response.StatusCode = 402; return context.Response.WriteAsync("Fell Through"); }); app.UseStageMarker(PipelineStage.MapHandler); }
public void Configuration(IAppBuilder app) { // this configures IdentityManager // we're using a Map just to test hosting not at the root app.Map("/idm", idm => { LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); var factory = new IdentityManagerServiceFactory(); var rand = new System.Random(); var users = Users.Get(rand.Next(5000, 20000)); var roles = Roles.Get(rand.Next(15)); factory.Register(new Registration <ICollection <InMemoryUser> >(users)); factory.Register(new Registration <ICollection <InMemoryRole> >(roles)); factory.IdentityManagerService = new Registration <IIdentityManagerService, InMemoryIdentityManagerService>(); idm.UseIdentityManager(new IdentityManagerOptions { Factory = factory, SecurityMode = SecurityMode.LocalMachine, OAuth2Configuration = new OAuth2Configuration { AuthorizationUrl = "http://localhost:17457/ids/connect/authorize", Issuer = "https://idsrv3.com", Audience = "https://idsrv3.com/resources", ClientId = "idmgr", SigningCert = Cert.Load(), Scope = "idmgr", ClaimsTransformation = user => { if (user.IsInRole("Foo")) { ((ClaimsIdentity)user.Identity).AddClaim(new Claim("role", "IdentityManagerAdministrator")); } return(user); }, //PersistToken = true, //AutomaticallyRenewToken = true } }); }); // this configures an embedded IdentityServer to act as an external authentication provider // when using IdentityManager in Token security mode. normally you'd configure this elsewhere. app.Map("/ids", ids => { IdSvrConfig.Configure(ids); }); // used to redirect to the main admin page visiting the root of the host app.Run(ctx => { ctx.Response.Redirect("/idm/"); return(System.Threading.Tasks.Task.FromResult(0)); }); }
public void TextHtmlAlpha(IAppBuilder app) { app.Run(context => { context.Response.ContentType = "text/html"; return(context.Response.WriteAsync("<p>alpha</p>")); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { context.Response.ContentType = "text/plain"; return(context.Response.WriteAsync("Hello World!")); }); }
public void DontAccessCertificate(IAppBuilder app) { app.Run(context => { context.Response.StatusCode = (int)CertNotFound; return(Task.FromResult(0)); }); }
//Obrigatório ter o método void Configuration public void Configuration(IAppBuilder app) { //responde a requisição http://localhost:8080/ app.Run(ctx => { return(ctx.Response.WriteAsync("Hello World in Katana!")); }); }
public void SetCustomUser(IAppBuilder app) { app.Run(context => { context.Request.User = new GenericPrincipal(new GenericIdentity("Bob"), null); return(context.Response.WriteAsync(Thread.CurrentPrincipal.Identity.Name)); }); }
public void DisableResponseBufferingApp(IAppBuilder app) { app.Run(context => { context.Get <Action>("server.DisableResponseBuffering")(); return(context.Response.WriteAsync("Hello World")); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { context.Response.ContentType = "text/html; charset=utf-8"; return(context.Response.WriteAsync("<h2> hello!<h2>")); }); }
public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888 app.Run(context => { context.Response.ContentType = "text/plain"; return(context.Response.WriteAsync("hello world.")); }); }
public void OnSendingHeadersException(IAppBuilder app) { app.Run(context => { context.Response.OnSendingHeaders(_ => { throw new Exception(); }, null); return(Task.FromResult(0)); }); }
public void Configuration(IAppBuilder app) { app.Run(context => { string t = DateTime.Now.Millisecond.ToString(); return(context.Response.WriteAsync(t + " Production OWIN App")); }); }