本文整理汇总了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;
}
示例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;
}
示例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));
}
示例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>();
}
示例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);
}
示例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;
}
示例7: AttachErrorResponse
private void AttachErrorResponse(NancyContext ctx)
{
if (ctx.ModelValidationResult.Errors.Count > 0)
{
ctx.Response.StatusCode = HttpStatusCode.BadRequest;
}
}
示例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;
}
示例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);
}
示例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;
}
}
}
示例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;
}
示例12: ConfigureRequestContainer
protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
base.ConfigureRequestContainer(container, context);
container.Register<IUserMapper, FakeRepository>();
container.Register<IRepository, FakeRepository>();
}
示例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();
};
}
示例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);
}
示例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() };
}