当前位置: 首页>>代码示例>>C#>>正文


C# OwinContext.Get方法代码示例

本文整理汇总了C#中OwinContext.Get方法的典型用法代码示例。如果您正苦于以下问题:C# OwinContext.Get方法的具体用法?C# OwinContext.Get怎么用?C# OwinContext.Get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在OwinContext的用法示例。


在下文中一共展示了OwinContext.Get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: UseHangfireServer

        public static IAppBuilder UseHangfireServer(
            [NotNull] this IAppBuilder builder,
            [NotNull] BackgroundJobServerOptions options,
            [NotNull] JobStorage storage)
        {
            if (builder == null) throw new ArgumentNullException("builder");
            if (options == null) throw new ArgumentNullException("options");
            if (storage == null) throw new ArgumentNullException("storage");

            var server = new BackgroundJobServer(options, storage);
            Servers.Add(server);

            var context = new OwinContext(builder.Properties);
            var token = context.Get<CancellationToken>("host.OnAppDisposing");
            if (token == default(CancellationToken))
            {
                // https://github.com/owin/owin/issues/27
                token = context.Get<CancellationToken>("server.OnDispose");
            }

            if (token == default(CancellationToken))
            {
                throw new InvalidOperationException("Current OWIN environment does not contain an instance of the `CancellationToken` class under `host.OnAppDisposing` key.");
            }

            token.Register(server.Dispose);

            return builder;
        }
开发者ID:djrineh,项目名称:Hangfire,代码行数:29,代码来源:AppBuilderExtensions.cs

示例2: ExpectedKeysAreAvailable

        public void ExpectedKeysAreAvailable()
        {
            var handler = new OwinClientHandler(env =>
            {
                IOwinContext context = new OwinContext(env);

                Assert.Equal("1.0", context.Get<string>("owin.Version"));
                Assert.NotNull(context.Get<CancellationToken>("owin.CallCancelled"));
                Assert.Equal("HTTP/1.1", context.Request.Protocol);
                Assert.Equal("GET", context.Request.Method);
                Assert.Equal("https", context.Request.Scheme);
                Assert.Equal(string.Empty, context.Get<string>("owin.RequestPathBase"));
                Assert.Equal("/A/Path/and/file.txt", context.Get<string>("owin.RequestPath"));
                Assert.Equal("and=query", context.Get<string>("owin.RequestQueryString"));
                Assert.NotNull(context.Request.Body);
                Assert.NotNull(context.Get<IDictionary<string, string[]>>("owin.RequestHeaders"));
                Assert.NotNull(context.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"));
                Assert.NotNull(context.Response.Body);
                Assert.Equal(200, context.Get<int>("owin.ResponseStatusCode"));
                Assert.Null(context.Get<string>("owin.ResponseReasonPhrase"));

                Assert.Equal("example.com", context.Request.Headers.Get("Host"));

                return Task.FromResult(0);
            });
            var httpClient = new HttpClient(handler);
            httpClient.GetAsync("https://example.com/A/Path/and/file.txt?and=query").Wait();
        }
开发者ID:Kstal,项目名称:Microsoft.Owin,代码行数:28,代码来源:OwinClientHandlerTests.cs

示例3: Invoke

        public async Task Invoke(IDictionary<string, object> env)
        {
            var context = new OwinContext(env);

            if (context.Request.Uri.Scheme != Uri.UriSchemeHttps)
            {
                context.Response.StatusCode = 403;
                context.Response.ReasonPhrase = "SSL is required.";

                return;
            }

            if (_options.RequireClientCertificate)
            {
                var cert = context.Get<X509Certificate2>("ssl.ClientCertificate");
                if (cert == null)
                {
                    context.Response.StatusCode = 403;
                    context.Response.ReasonPhrase = "SSL client certificate is required.";

                    return;
                }
            }

            await _next(env);
        }
开发者ID:RyanLiu99,项目名称:Thinktecture.IdentityModel,代码行数:26,代码来源:RequireSslMiddleware.cs

示例4: Configuration

        public void Configuration(IAppBuilder app)
        {
            // Loads the config from our App.config
            XmlConfigurator.Configure();

            // MassTransit to use Log4Net
            Log4NetLogger.Use();

            var container = IocConfig.RegisterDependencies();

            // Sets the Mvc resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Sets Mvc Owin resolver as well
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            // Starts Mass Transit Service bus, and registers stopping of bus on app dispose
            var bus = container.Resolve<IBusControl>();
            var busHandle = bus.StartAsync().Result;

            if (app.Properties.ContainsKey("host.OnAppDisposing"))
            {
                var context = new OwinContext(app.Properties);
                var token = context.Get<CancellationToken>("host.OnAppDisposing");
                if (token != CancellationToken.None)
                {
                    token.Register(() => busHandle.Stop(TimeSpan.FromSeconds(30)));
                }
            }
        }
开发者ID:maldworth,项目名称:tutorial-masstransit-send-vs-publish,代码行数:31,代码来源:Startup.cs

示例5: SignOutTwice_Cumulative

 public void SignOutTwice_Cumulative()
 {
     IOwinContext context = new OwinContext();
     context.Authentication.SignOut("foo");
     context.Authentication.SignOut("bar");
     Assert.Equal(new[] { "foo", "bar" }, context.Get<string[]>("security.SignOut"));
 }
开发者ID:Kstal,项目名称:Microsoft.Owin,代码行数:7,代码来源:AuthenticationManagerTests.cs

示例6: ParseAsync

        /// <summary>
        /// Tries to find a secret on the environment that can be used for authentication
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <returns>
        /// A parsed secret
        /// </returns>
        public async Task<ParsedSecret> ParseAsync(IDictionary<string, object> environment)
        {
            Logger.Debug("Start parsing for X.509 certificate");

            var context = new OwinContext(environment);
            var body = await context.ReadRequestFormAsync();

            if (body == null)
            {
                return null;
            }

            var id = body.Get("client_id");
            if (id.IsMissing())
            {
                Logger.Debug("client_id is not found in post body");
                return null;
            }

            var cert = context.Get<X509Certificate2>("ssl.ClientCertificate");

            if (cert != null)
            {
                return new ParsedSecret
                {
                    Id = id,
                    Credential = cert,
                    Type = Constants.ParsedSecretTypes.X509Certificate
                };
            }

            Logger.Debug("X.509 certificate not found.");
            return null;
        }
开发者ID:Rolosoft,项目名称:IdentityServer3,代码行数:41,代码来源:X509CertificateSecretParser.cs

示例7: RegisterOnAppDisposing

 /// <summary>
 /// Registers the on application disposing method.
 /// </summary>
 /// <param name="app">The application.</param>
 /// <param name="cleanUpMethod">The clean up method.</param>
 public static void RegisterOnAppDisposing(this IAppBuilder app, Action cleanUpMethod)
 {
     var context = new OwinContext(app.Properties);
     var token = context.Get<CancellationToken>("host.OnAppDisposing");
     if (token != CancellationToken.None)
     {
         token.Register(cleanUpMethod);
     }
 }
开发者ID:yocos,项目名称:iHUD,代码行数:14,代码来源:OwinExtensions.cs

示例8: ConfigureShutdown

 private void ConfigureShutdown(IAppBuilder appBuilder)
 {
     var context = new OwinContext(appBuilder.Properties);
     var token = context.Get<CancellationToken>("host.OnAppDisposing");
     if (token != CancellationToken.None)
     {
         token.Register(Shutdown);
     }
 }
开发者ID:AndriyKhavro,项目名称:Parcs.NET,代码行数:9,代码来源:Startup.cs

示例9: Invoke

        /// <summary>
        /// Adds the sendfile.SendAsync Func to the request environment, if not already present.
        /// </summary>
        /// <param name="environment">OWIN environment dictionary which stores state information about the request, response and relevant server state.</param>
        /// <returns></returns>
        public Task Invoke(IDictionary<string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);

            // Check if there is a SendFile delegate already presents
            if (context.Get<object>(Constants.SendFileAsyncKey) as SendFileFunc == null)
            {
                context.Set<SendFileFunc>(Constants.SendFileAsyncKey, new SendFileFunc(new SendFileWrapper(context.Response.Body).SendAsync));
            }

            return _next(environment);
        }
开发者ID:Kstal,项目名称:Microsoft.Owin,代码行数:17,代码来源:SendFileMiddleware.cs

示例10: Configuration

        public void Configuration(IAppBuilder app)
        {
            //ConfigureAuth(app);
            CouchbaseConfig.Initialize();

            var context = new OwinContext(app.Properties);
            var token = context.Get<CancellationToken>("host.OnAppDisposing");
            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    // code to run on shutdown
                    CouchbaseConfig.Close();
                });
            }
        }
开发者ID:boblarson57,项目名称:try-cb-dotnet,代码行数:16,代码来源:Startup.cs

示例11: RunHangfireServer

        public static void RunHangfireServer(
            this IAppBuilder app,
            BackgroundJobServer server)
        {
            Servers.Add(server);

            server.Start();

            var context = new OwinContext(app.Properties);
            var token = context.Get<CancellationToken>("host.OnAppDisposing");

            if (token != CancellationToken.None)
            {
                token.Register(server.Dispose);
            }
        }
开发者ID:harriyott,项目名称:Hangfire,代码行数:16,代码来源:ServerOwinExtensions.cs

示例12: Configuration

        public void Configuration(IAppBuilder app)
        {
            // Loads the config from our App.config
            XmlConfigurator.Configure();

            // MassTransit to use Log4Net
            Log4NetLogger.Use();

            var container = IocConfig.RegisterDependencies();

            // Get your HubConfiguration. In OWIN, we create one rather than using GlobalHost
            var hubConfig = new HubConfiguration();

            // Sets the dependency resolver to be autofac.
            hubConfig.Resolver = new AutofacSignalR.AutofacDependencyResolver(container);

            // Sets the Mvc resolver
            DependencyResolver.SetResolver(new AutofacMvc.AutofacDependencyResolver(container));

            // Sets SignalR and Mvc Owin resolver as well
            app.UseAutofacMiddleware(container);
            app.MapSignalR("/signalr", hubConfig);
            app.UseAutofacMvc();

            // There's not a lot of documentation or discussion for owin getting the hubcontext
            // Got this from here: https://stackoverflow.com/questions/29783898/owin-signalr-autofac
            var builder = new ContainerBuilder();
            var connManager = hubConfig.Resolver.Resolve<IConnectionManager>();
            builder.RegisterInstance(connManager)
                .As<IConnectionManager>()
                .SingleInstance();
            builder.Update(container);

            // Starts Mass Transit Service bus, and registers stopping of bus on app dispose
            var bus = container.Resolve<IBusControl>();
            var busHandle = bus.Start();

            if (app.Properties.ContainsKey("host.OnAppDisposing"))
            {
                var context = new OwinContext(app.Properties);
                var token = context.Get<CancellationToken>("host.OnAppDisposing");
                if (token != CancellationToken.None)
                {
                    token.Register(() => busHandle.Stop(TimeSpan.FromSeconds(30)));
                }
            }
        }
开发者ID:maldworth,项目名称:StarterKit-Autofac-MassTransit-Mvc-SignalR,代码行数:47,代码来源:Startup.cs

示例13: Invoke

        public async Task Invoke(IDictionary<string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);

            var path = context.Request.Path;

            var accept = context.Get<WebSocketAccept>("websocket.Accept");
            if (accept != null)
            {
                accept(null, WebSocketChat);
                return;
            }
            
            PathString remainingPath;
            if (!path.StartsWithSegments(_pathString, out remainingPath))
            {
                await _next(environment);
                return;
            }
            if (remainingPath.StartsWithSegments(new PathString("/god")))
            {
                context.Response.Headers.Add("Content-type", new[] {"text/plain; charset=utf-8"});
                var text = context.Request.Query.Get("text");
                if (text != null)
                {
                    var jsonData =
                        JsonConvert.SerializeObject(new ChatText
                        {
                            IsGod = true,
                            Color = "#FF0000",
                            Text = "神は言っている、" + text + " と"
                        });
                    _notifyAll.OnNext(new ChatEchoData(jsonData, 1, true));
                    await context.Response.WriteAsync("神は言っている、 送信が完了したと");
                    return;
                }
                await context.Response.WriteAsync("そんなクエリで大丈夫か\ntext=[メッセージ]で頼む");
                return;
            }
            //ページを表示
            context.Response.Headers.Add("Content-type", new[] {"text/html; charset=utf-8"});
            await context.Response.WriteAsync(_templateService.Display("Room.cshtml", _room, null, null));
        }
开发者ID:hungdluit,项目名称:ImageChat,代码行数:43,代码来源:RoomMiddleware.cs

示例14: Invoke

        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="env">The OWIN environment.</param>
        /// <returns></returns>
        public async Task Invoke(IDictionary<string, object> env)
        {
            var context = new OwinContext(env);

            // if no token was sent - no need to validate scopes
            var principal = context.Authentication.User;
            if (principal == null || principal.Identity == null || !principal.Identity.IsAuthenticated)
            {
                await _next(env);
                return;
            }

            var token = context.Get<string>("idsrv:tokenvalidation:token");
            if (!string.IsNullOrWhiteSpace(token))
            {
                principal.Identities.First().AddClaim(new Claim("token", token));
            }

            await _next(env);
        }
开发者ID:ryanmar,项目名称:IdentityServer3.AccessTokenValidation,代码行数:25,代码来源:PreserveAccessTokenMiddleware.cs

示例15: Invoke

        public async Task Invoke(IDictionary<string, object> env)
        {
            logger.Begin();
            IOwinContext context = new OwinContext(env);
            WebSocketAccept accept = context.Get<WebSocketAccept>(Constants.OWIN_WEBSOCKET_ACCEPT);
            if (accept != null)
            {
                var requestPath = context.Request.Path.ToString().Substring(1);
                var isPath = requestPath.Equals(path, StringComparison.OrdinalIgnoreCase);

                logger.Trace("Websocket upgrade request to path: {0}", requestPath);
                if (isPath)
                {
                    accept(null, Callback);
                    return;
                }
            }

            await next.Invoke(context.Environment);

            logger.End();
            return;
        }
开发者ID:inuplan,项目名称:intranet,代码行数:23,代码来源:WebSocketMiddleware.cs


注:本文中的OwinContext.Get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。