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


C# Nancy.NancyContext类代码示例

本文整理汇总了C#中Nancy.NancyContext的典型用法代码示例。如果您正苦于以下问题:C# NancyContext类的具体用法?C# NancyContext怎么用?C# NancyContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: OnError

        private static Response OnError(NancyContext context, Exception exception) {
            var contextData = new Dictionary<string, object> { { NANCY_CONTEXT, context } };

            ExceptionlessClient.Current.ProcessUnhandledException(exception, "NancyPipelineException", true, contextData);

            return context.Response;
        }
开发者ID:priestd09,项目名称:Exceptionless,代码行数:7,代码来源:ExceptionlessNancyExtensions.cs

示例2: LogRequest

        private Response LogRequest(NancyContext ctx)
        {
            _logger.Debug("************ Request ************");
            _logger.Debug("{0} - {1}", ctx.Request.Method, ctx.Request.Path);
            _logger.Debug("************ Headers ************");

            foreach(var headerGroup in ctx.Request.Headers)
            {
                foreach(var header in headerGroup.Value)
                {
                    _logger.Debug("{0} - {1}", headerGroup.Key, header);
                }
            }

            _logger.Debug("************  Body ************");
            using (var reader = new StreamReader(ctx.Request.Body))
            {
                var content = reader.ReadToEnd();
                _logger.Debug(HttpUtility.UrlDecode(content));
            }

            ctx.Request.Body.Position = 0;

            return null;
        }
开发者ID:lorry-lee,项目名称:vimlorry,代码行数:25,代码来源:Bootstrapper.cs

示例3: Handle_WhenTestContextIsSetOnTheRepository_DoesNotLogTheTextContext

        public void Handle_WhenTestContextIsSetOnTheRepository_DoesNotLogTheTextContext()
        {
            const string testContext = "EventsApiConsumerTests.GetAllEvents_WhenCalled_ReturnsAllEvents";
            var headers = new Dictionary<string, IEnumerable<string>>
            {
                { Constants.AdministrativeRequestTestContextHeaderKey, new List<string> { testContext } }
            };

            var context = new NancyContext
            {
                Request = new Request("DELETE", new Url
                {
                    Path = "/interactions",
                    Scheme = "http"
                }, null, headers)
            };

            var handler = GetSubject();

            _mockProviderRepository.TestContext.Returns(testContext);

            handler.Handle(context);

            _mockLog.Received(0).Log(LogLevel.Info, Arg.Any<Func<string>>(), null, Arg.Is<object[]>(x => x.Single() == testContext));
        }
开发者ID:humblelistener,项目名称:pact-net,代码行数:25,代码来源:MockProviderAdminRequestHandlerTests.cs

示例4: ConfigureRequestContainer

 protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
 {
     base.ConfigureRequestContainer(container, context);
     var ctx = new SmartFlowContext();
     container.Register(ctx);
     container.Register<IUserMapper, SmartFlowAuthService>();
 }
开发者ID:DeanMcgarrigle,项目名称:SmartFlow,代码行数:7,代码来源:Bootstrapper.cs

示例5: Initialize

        /// <summary>
        /// Perform any initialisation tasks
        /// </summary>
        /// <param name="pipelines">Application pipelines</param>
        /// <param name="context">The current context</param>
        public void Initialize(IPipelines pipelines, NancyContext context)
        {
            // On each request, store the NancyContext in the LogicalCallContext
            CallContext.LogicalSetData(NancyConfiguration.NancyContextDataSlot, context);

            var nancyConfiguration = NancyConfiguration.Settings;
            if (nancyConfiguration == null)
                return;

            var name = nancyConfiguration.PipelineName.Value;
            var sharpRaven = new PipelineItem(name, (nancyContext, exception) =>
            {
                if (nancyConfiguration.CaptureExceptionOnError.Value)
                {
                    var guid = this.ravenClient.CaptureException(exception);

                    if (guid != null)
                    {
                        context.Items.Add(NancyConfiguration.SentryEventGuidKey, guid);
                        exception.Data.Add(NancyConfiguration.SentryEventGuidKey, guid);
                    }
                }

                return null;
            });

            pipelines.OnError.AddItemToStartOfPipeline(sharpRaven);
        }
开发者ID:getsentry,项目名称:raven-csharp,代码行数:33,代码来源:SentryRequestStartup.cs

示例6: SetCache

        /// <summary>
        /// Adds the current response to the cache if required
        /// Only stores by Path and stores the response in a dictionary.
        /// Do not use this as an actual cache :-)
        /// </summary>
        /// <param name="context">Current context</param>
        public void SetCache(NancyContext context)
        {
            if (context.Response.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            object cacheSecondsObject;
            if (!context.Items.TryGetValue(ContextExtensions.OUTPUT_CACHE_TIME_KEY, out cacheSecondsObject))
            {
                return;
            }

            int cacheSeconds;
            if (!int.TryParse(cacheSecondsObject.ToString(), out cacheSeconds))
            {
                return;
            }

            var cachedResponse = new CachedResponse(context.Response);

            this.cachedResponses[context.Request.Path] = new Tuple<DateTime, Response, int>(DateTime.Now, cachedResponse, cacheSeconds);

            context.Response = cachedResponse;
        }
开发者ID:nathanpalmer,项目名称:Nancy,代码行数:31,代码来源:CachingBootstrapper.cs

示例7: AttachErrorResponse

 private void AttachErrorResponse(NancyContext ctx)
 {
     if (ctx.ModelValidationResult.Errors.Count > 0)
     {
         ctx.Response.StatusCode = HttpStatusCode.BadRequest;
     }
 }
开发者ID:ninjabadgerpirate,项目名称:RequireNancySinatra,代码行数:7,代码来源:Bootstrapper.cs

示例8: IsCacheable

        public bool IsCacheable(NancyContext context)
        {
            if (!RuntimeInfoBase.IsProduction)
            {
                return false;
            }

            if (((DynamicDictionary)context.Request.Query).ContainsKey("h")) return true;

            if (context.Request.Path.StartsWith("/api", StringComparison.CurrentCultureIgnoreCase))
            {
                if (context.Request.Path.ContainsIgnoreCase("/MediaCover")) return true;

                return false;
            }

            if (context.Request.Path.StartsWith("/signalr", StringComparison.CurrentCultureIgnoreCase)) return false;
            if (context.Request.Path.EndsWith("main.js")) return false;
            if (context.Request.Path.StartsWith("/feed", StringComparison.CurrentCultureIgnoreCase)) return false;

            if (context.Request.Path.StartsWith("/log", StringComparison.CurrentCultureIgnoreCase) &&
                context.Request.Path.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase))
            {
                return false;
            }

            if (context.Response != null)
            {
                if (context.Response.ContentType.Contains("text/html")) return false;
            }

            return true;
        }
开发者ID:Djohnnie,项目名称:Sonarr,代码行数:33,代码来源:CacheableSpecification.cs

示例9: RequestStartup

        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(requestContainer, pipelines, context);

            // At request startup we modify the request pipelines to
            // include forms authentication - passing in our now request
            // scoped user name mapper.
            //
            // The pipelines passed in here are specific to this request,
            // so we can add/remove/update items in them as we please.
            var loginService = requestContainer.Resolve<LoginService>();
            var authConfiguration =
                new StatelessAuthenticationConfiguration(c =>
                {
                    var apiKeyFromRequest = ((DynamicDictionaryValue)c.Request.Query.ApiKey).Value as ApiKey
                        ?? ((DynamicDictionaryValue)c.Request.Form.ApiKey).Value as ApiKey;

                    if (apiKeyFromRequest == null) return null;

                    if (loginService.IsApiKeyValid(apiKeyFromRequest))
                    {
                        return new UserIdentity(apiKeyFromRequest.Username, new List<string>());
                    }
                    return null;
                });

            StatelessAuthentication.Enable(pipelines, authConfiguration);
        }
开发者ID:goranobradovic,项目名称:niccom.net,代码行数:28,代码来源:Bootstrapper.cs

示例10: CacheCheck

    public void CacheCheck(NancyContext context)
    {

      var responseHeaders = context.Response.Headers;
      var requestHeaders = context.Request.Headers;

      string currentFileEtag;
      if (responseHeaders.TryGetValue("ETag", out currentFileEtag))
      {
        if (requestHeaders.IfNoneMatch.Contains(currentFileEtag))
        {
          context.Response = HttpStatusCode.NotModified;
          return;
        }
      }

      string responseLastModifiedString;
      if (responseHeaders.TryGetValue("Last-Modified", out responseLastModifiedString))
      {
        var responseLastModified = DateTime.ParseExact(responseLastModifiedString, "R", CultureInfo.InvariantCulture, DateTimeStyles.None);
        if (responseLastModified <= requestHeaders.IfModifiedSince)
        {
          context.Response = HttpStatusCode.NotModified;
        }
      }
    }
开发者ID:skinny,项目名称:Cassette.Nancy,代码行数:26,代码来源:RawFileRequestRewriter.cs

示例11: Collect

        public static RequestInfo Collect(NancyContext context, ExceptionlessClient client) {
            if (context == null)
                return null;

            var info = new RequestInfo {
                ClientIpAddress = context.Request.UserHostAddress,
                HttpMethod = context.Request.Method
            };

            if (context.Request.Headers.UserAgent != null)
                info.UserAgent = context.Request.Headers.UserAgent;

            if (context.Request.Url != null) {
                info.Host = context.Request.Url.HostName;
                info.IsSecure = context.Request.Url.IsSecure;
                info.Path = context.Request.Url.BasePath + context.Request.Url.Path;
                info.Port = context.Request.Url.Port ?? 80;
            }

            if (context.Request.Headers.Referrer != null)
                info.Referrer = context.Request.Headers.Referrer;

            info.Cookies = context.Request.Cookies.ToDictionary(client);

            if (context.Request.Url != null && !String.IsNullOrWhiteSpace(context.Request.Url.Query))
                info.QueryString = HttpUtility.ParseQueryString(context.Request.Url.Query).ToDictionary(client);

            return info;
        }
开发者ID:priestd09,项目名称:Exceptionless,代码行数:29,代码来源:NancyRequestInfoCollector.cs

示例12: ConfigureRequestContainer

        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);

            container.Register<IUserMapper, FakeRepository>();
            container.Register<IRepository, FakeRepository>();
        }
开发者ID:markashleybell,项目名称:gtdpad,代码行数:7,代码来源:TestBootstrapper.cs

示例13: RewriteResponseContents

    public void RewriteResponseContents(NancyContext context)
    {
      if (!context.Response.ContentType.Equals("text/html"))
      {
        // Only html needs to be (possibly) rewritten
        return;
      }
      var currentContents = context.Response.Contents;
      context.Response.Contents =
        stream =>
        { 
          var placeholderTracker = Container.Resolve<IPlaceholderTracker>();

          var currentContentsStream = new MemoryStream();
          currentContents(currentContentsStream);
          var reader = new StreamReader(currentContentsStream);

          reader.BaseStream.Seek(0, SeekOrigin.Begin);
          var writer = new StreamWriter(stream);
          
          writer.Write(placeholderTracker.ReplacePlaceholders(reader.ReadToEnd()));
          
          writer.Flush();
        };
    }
开发者ID:marcusoftnet,项目名称:Cassette.Nancy,代码行数:25,代码来源:WebHost.cs

示例14: Handle_WhenExpectedResponseHasNotBeenSet_ResponseMapperIsCalledAndReturns500Response

        public void Handle_WhenExpectedResponseHasNotBeenSet_ResponseMapperIsCalledAndReturns500Response()
        {
            var nancyContext = new NancyContext
            {
                Request = new Request("GET", "/", "HTTP")
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = null }
            };

            nancyContext.SetMockInteraction(interactions);

            var mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();
            var mockProviderRepository = Substitute.For<IMockProviderRepository>();

            mockResponseMapper.Convert(Arg.Any<ProviderServiceResponse>())
                .Returns(new Response
                {
                    StatusCode = HttpStatusCode.InternalServerError
                });

            IMockProviderRequestHandler handler = new MockProviderRequestHandler(mockRequestMapper, mockResponseMapper, mockProviderRepository);

            var result = handler.Handle(nancyContext);

            mockResponseMapper.Received(1).Convert(Arg.Is<ProviderServiceResponse>(x => x.Status == 500));
            Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode);
        }
开发者ID:screamish,项目名称:pact-net,代码行数:31,代码来源:MockProviderRequestHandlerTests.cs

示例15: GetUserFromIdentifier

        public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
        {
            string userGuid = identifier.ToString();
            var user = this.Repository.Find<User>(x => x.Guid == userGuid).SingleOrDefault();

            return user == null ? null : new PlayerIdentity() { UserName = user.Id.ToString() };
        }
开发者ID:nfink,项目名称:Haven,代码行数:7,代码来源:UserMapper.cs


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