本文整理汇总了C#中NancyContext类的典型用法代码示例。如果您正苦于以下问题:C# NancyContext类的具体用法?C# NancyContext怎么用?C# NancyContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
NancyContext类属于命名空间,在下文中一共展示了NancyContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Filter
/// <summary>
/// Applies a filter to the provided list of routes. Routes that do not pass the filter will be places in the second item of the returned tuple
/// along with the provided <paramref name="rejectReason"/>.
/// </summary>
/// <param name="routes">The routes that the filter should be applied to.</param>
/// <param name="context">The context of the current request.</param>
/// <param name="rejectReason">The message that should be attached to rejected routes.</param>
/// <param name="condition">The condition that routes need to fulfill.</param>
/// <returns>A tuple of valid and rejected routes.</returns>
public static Tuple<List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>, Dictionary<string, List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>>> Filter(this Tuple<List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>, Dictionary<string, List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>>> routes, NancyContext context, string rejectReason, Func<NancyContext, Tuple<string, int, RouteDescription, IRoutePatternMatchResult>, Tuple<bool, Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>> condition)
{
var result = new Tuple<List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>, Dictionary<string, List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>>>(
new List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>(),
routes.Item2
);
foreach (var conditionResult in routes.Item1.Select(route => condition.Invoke(context, route)))
{
if (conditionResult.Item1)
{
result.Item1.Add(conditionResult.Item2);
}
else
{
if (!result.Item2.ContainsKey(rejectReason))
{
result.Item2.Add(rejectReason, new List<Tuple<string, int, RouteDescription, IRoutePatternMatchResult>>());
}
result.Item2[rejectReason].Add(conditionResult.Item2);
}
}
return result;
}
开发者ID:RobertTheGrey,项目名称:Nancy,代码行数:35,代码来源:RouteCandidateExtensions.cs
示例2: Bind
/// <summary>
/// Bind to the given model type
/// </summary>
/// <param name="context">Current context</param>
/// <param name="modelType">Model type to bind to</param>
/// <param name="instance">Optional existing instance</param>
/// <param name="configuration">The <see cref="BindingConfig" /> that should be applied during binding.</param>
/// <param name="blackList">Blacklisted property names</param>
/// <returns>Bound model</returns>
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration,
params string[] blackList)
{
Type genericType = null;
if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())
{
//make sure it has a generic type
if (modelType.IsGenericType())
{
genericType = modelType.GetGenericArguments().FirstOrDefault();
}
else
{
var implementingIEnumerableType =
modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault(
i => i.GetGenericTypeDefinition() == typeof (IEnumerable<>));
genericType = implementingIEnumerableType == null ? null : implementingIEnumerableType.GetGenericArguments().FirstOrDefault();
}
if (genericType == null)
{
throw new ArgumentException("When modelType is an enumerable it must specify the type", "modelType");
}
}
var bindingContext =
CreateBindingContext(context, modelType, instance, configuration, blackList, genericType);
var bodyDeserializedModel = DeserializeRequestBody(bindingContext);
return (instance as IEnumerable<string>) ?? bodyDeserializedModel;
}
开发者ID:dmitriylyner,项目名称:ServiceControl,代码行数:41,代码来源:StringListBinder.cs
示例3: Should_apply_default_accept_when_no_accept_header_sent
public void Should_apply_default_accept_when_no_accept_header_sent()
{
// Given
var browser = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(new ConfigurableNancyModule(x =>
{
x.Get("/", parameters =>
{
var context =
new NancyContext { NegotiationContext = new NegotiationContext() };
var negotiator =
new Negotiator(context);
return negotiator;
});
}));
});
// When
var response = browser.Get("/");
// Then
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
开发者ID:uxTomas,项目名称:Nancy,代码行数:28,代码来源:ContentNegotiationFixture.cs
示例4: Resolve
/// <summary>
/// Gets the route, and the corresponding parameter dictionary from the URL
/// </summary>
/// <param name="context">Current context</param>
/// <param name="routeCache">Route cache</param>
/// <returns>Tuple - Item1 being the Route, Item2 being the parameters dictionary, Item3 being the prereq, Item4 being the postreq</returns>
public ResolveResult Resolve(NancyContext context, IRouteCache routeCache)
{
if (routeCache.IsEmpty())
{
return new ResolveResult(new NotFoundRoute(context.Request.Method, context.Request.Uri), DynamicDictionary.Empty, null, null);
}
var routesThatMatchRequestedPath = this.GetRoutesThatMatchRequestedPath(routeCache, context);
if (NoRoutesWereAbleToBeMatchedInRouteCache(routesThatMatchRequestedPath))
{
return new ResolveResult(new NotFoundRoute(context.Request.Method, context.Request.Uri), DynamicDictionary.Empty, null, null);
}
var routesWithCorrectRequestMethod =
GetRoutesWithCorrectRequestMethod(context.Request, routesThatMatchRequestedPath);
if (NoRoutesWereForTheRequestedMethod(routesWithCorrectRequestMethod))
{
return new ResolveResult(new MethodNotAllowedRoute(context.Request.Uri, context.Request.Method), DynamicDictionary.Empty, null, null);
}
var routeMatchesWithMostParameterCaptures =
GetRouteMatchesWithMostParameterCaptures(routesWithCorrectRequestMethod);
var routeMatchToReturn =
GetSingleRouteToReturn(routeMatchesWithMostParameterCaptures);
return this.CreateRouteAndParametersFromMatch(context, routeMatchToReturn);
}
开发者ID:slai,项目名称:cwkb,代码行数:36,代码来源:DefaultRouteResolver.cs
示例5: BuildHypermedia
private dynamic BuildHypermedia(object model, NancyContext context)
{
if (model == null) return null;
if (model is IEnumerable)
{
//how to handle a collection at the root resource level?
return ((IEnumerable)model).Cast<object>().Select(x => BuildHypermedia(x, context));
}
IDictionary<string, object> halModel = model.ToDynamic();
var typeConfig = configuration.GetTypeConfiguration(model.GetType());
if (typeConfig == null) return halModel;
var links = typeConfig.LinksFor(model, context).ToArray();
if (links.Any())
halModel["_links"] = links.GroupBy(l => l.Rel).ToDictionary(grp => grp.Key, grp => BuildDynamicLinksOrLink(grp));
var embeddedResources = typeConfig.Embedded().ToArray();
if (embeddedResources.Any())
{
// Remove original objects from the model (if they exist)
foreach (var embedded in embeddedResources)
halModel.Remove(embedded.OriginalPropertyName);
halModel["_embedded"] = embeddedResources.ToDictionary(info => info.Rel, info => BuildHypermedia(info.GetEmbeddedResource(model), context));
}
var ignoredProperties = typeConfig.Ignored().ToArray();
if (ignoredProperties.Any())
{
//remove ignored properties from the output
foreach (var ignored in ignoredProperties) halModel.Remove(ignored);
}
return halModel;
}
开发者ID:MrScruffy04,项目名称:Nancy.Hal,代码行数:35,代码来源:HalJsonResponseProcessor.cs
示例6: NancyEngineFixture
public NancyEngineFixture()
{
this.resolver = A.Fake<IRouteResolver>();
this.response = new Response();
this.route = new FakeRoute(response);
this.context = new NancyContext();
this.errorHandler = A.Fake<IErrorHandler>();
this.requestDispatcher = A.Fake<IRequestDispatcher>();
A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._)).Invokes(x => this.context.Response = new Response());
A.CallTo(() => errorHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);
contextFactory = A.Fake<INancyContextFactory>();
A.CallTo(() => contextFactory.Create()).Returns(context);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null, null));
var applicationPipelines = new Pipelines();
this.routeInvoker = A.Fake<IRouteInvoker>();
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg =>
{
return (Response)((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1]);
});
this.engine =
new NancyEngine(this.requestDispatcher, contextFactory, new[] { this.errorHandler }, A.Fake<IRequestTracing>())
{
RequestPipelinesFactory = ctx => applicationPipelines
};
}
开发者ID:rhwy,项目名称:Nancy,代码行数:33,代码来源:NancyEngineFixture.cs
示例7: CanProcess
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
if (IsExactSirenContentType(requestedMediaRange))
{
return new ProcessorMatch
{
ModelResult = MatchResult.DontCare,
RequestedContentTypeResult = MatchResult.ExactMatch
};
}
if (IsWildcardSirenContentType(requestedMediaRange))
{
return new ProcessorMatch
{
ModelResult = MatchResult.DontCare,
RequestedContentTypeResult = MatchResult.NonExactMatch
};
}
return new ProcessorMatch
{
ModelResult = MatchResult.DontCare,
RequestedContentTypeResult = MatchResult.NoMatch
};
}
开发者ID:madhon,项目名称:NancyHelloWorld,代码行数:26,代码来源:SirenResponseProcessor.cs
示例8: ResponseManipulatorForSessionFixture
public ResponseManipulatorForSessionFixture() {
_responseManipulatorForSession = new ResponseManipulatorForSession();
_context = new NancyContext {Response = new Response(), Request = new Request("GET", "http://www.google.be")};
_sessionIdentificationData = new SessionIdentificationData {SessionId = "01SessionId", Hmac = new byte[] {211, 81, 204, 0, 47, 124}};
_parameterName = "SID";
}
开发者ID:DavidLievrouw,项目名称:Nancy.Session.InProc,代码行数:7,代码来源:ResponseManipulatorForSessionFixture.cs
示例9: UserLoggedInRedirectResponse
/// <summary>
/// Creates a response that sets the authentication cookie and redirects
/// the user back to where they came from.
/// </summary>
/// <param name="context">Current context</param>
/// <param name="userIdentifier">User identifier guid</param>
/// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
/// <param name="fallbackRedirectUrl">Url to redirect to if none in the querystring</param>
/// <returns>Nancy response with redirect.</returns>
public static Response UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = null)
{
var redirectUrl = fallbackRedirectUrl;
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = context.Request.Url.BasePath;
}
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = "/";
}
string redirectQuerystringKey = GetRedirectQuerystringKey(currentConfiguration);
if (context.Request.Query[redirectQuerystringKey].HasValue)
{
var queryUrl = (string)context.Request.Query[redirectQuerystringKey];
if (context.IsLocalUrl(queryUrl))
{
redirectUrl = queryUrl;
}
}
var response = context.GetRedirect(redirectUrl);
var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
开发者ID:Borzoo,项目名称:Nancy,代码行数:41,代码来源:FormsAuthentication.cs
示例10: Tokenize
/// <summary>
/// Creates a token from a <see cref="IUserIdentity"/>.
/// </summary>
/// <param name="userIdentity">The user identity from which to create a token.</param>
/// <param name="context">Current <see cref="NancyContext"/>.</param>
/// <returns>The generated token.</returns>
public string Tokenize(IUserIdentity userIdentity, NancyContext context)
{
var items = new List<string>
{
userIdentity.UserName,
string.Join(this.claimsDelimiter, userIdentity.Claims),
this.tokenStamp().Ticks.ToString(CultureInfo.InvariantCulture)
};
if (this.additionalItems != null)
{
foreach (var item in this.additionalItems.Select(additionalItem => additionalItem(context)))
{
if (string.IsNullOrWhiteSpace(item))
{
throw new RouteExecutionEarlyExitException(new Response { StatusCode = HttpStatusCode.Unauthorized });
}
items.Add(item);
}
}
var message = string.Join(this.itemDelimiter, items);
var token = CreateToken(message);
return token;
}
开发者ID:jbattermann,项目名称:Nancy,代码行数:31,代码来源:Tokenizer.cs
示例11: Should_add_negotiated_content_headers_to_response
public void Should_add_negotiated_content_headers_to_response()
{
// Given
var module = new ConfigurableNancyModule(with =>
{
with.Get("/headers", (x, m) =>
{
var context =
new NancyContext { NegotiationContext = new NegotiationContext() };
var negotiator =
new Negotiator(context);
negotiator.WithContentType("text/xml");
return negotiator;
});
});
var brower = new Browser(with =>
{
with.ResponseProcessor<TestProcessor>();
with.Module(module);
});
// When
var response = brower.Get("/headers");
// Then
Assert.Equal("text/xml", response.Context.Response.ContentType);
}
开发者ID:garethrhughes,项目名称:Nancy,代码行数:32,代码来源:ContentNegotiationFixture.cs
示例12: BuildMethodNotAllowedResult
private static ResolveResult BuildMethodNotAllowedResult(NancyContext context, IEnumerable<string> allowedMethods)
{
var route =
new MethodNotAllowedRoute(context.Request.Path, context.Request.Method, allowedMethods);
return new ResolveResult(route, new DynamicDictionary(), null, null, null);
}
开发者ID:RadifMasud,项目名称:Nancy,代码行数:7,代码来源:DefaultRouteResolver.cs
示例13: Invoke
/// <summary>
/// Invokes the specified <paramref name="route"/> with the provided <paramref name="parameters"/>.
/// </summary>
/// <param name="route">The route that should be invoked.</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <param name="parameters">The parameters that the route should be invoked with.</param>
/// <param name="context">The context of the route that is being invoked.</param>
/// <returns>A <see cref="Response"/> instance that represents the result of the invoked route.</returns>
public async Task<Response> Invoke(Route route, CancellationToken cancellationToken, DynamicDictionary parameters, NancyContext context)
{
object result;
try
{
result = await route.Invoke(parameters, cancellationToken).ConfigureAwait(false);
}
catch(RouteExecutionEarlyExitException earlyExitException)
{
context.WriteTraceLog(
sb => sb.AppendFormat(
"[DefaultRouteInvoker] Caught RouteExecutionEarlyExitException - reason {0}",
earlyExitException.Reason));
return earlyExitException.Response;
}
if (!(result is ValueType) && result == null)
{
context.WriteTraceLog(
sb => sb.AppendLine("[DefaultRouteInvoker] Invocation of route returned null"));
result = new Response();
}
return this.negotiator.NegotiateResponse(result, context);
}
开发者ID:RadifMasud,项目名称:Nancy,代码行数:35,代码来源:DefaultRouteInvoker.cs
示例14: SaveSession
private static void SaveSession(NancyContext ctx, IKeyValueStore store)
{
if (ctx.Request == null || ctx.Request.Session == null || !ctx.Request.Session.HasChanged)
return;
string id;
if (ctx.Request.Cookies.ContainsKey(GetCookieName()))
{
id = ctx.Request.Cookies[GetCookieName()];
}
else
{
// TODO: Should we give a way to override how the id is generated?
// TODO: Should we encrypt / hash the id so people can not just try out other values?
id = Guid.NewGuid().ToString();
ctx.Response.AddCookie(GetCookieName(), id);
}
IDictionary<string, object> items = new Dictionary<string, object>();
foreach (var item in ctx.Request.Session)
{
items.Add(item.Key, item.Value);
}
store.Save(id, items);
}
开发者ID:csainty,项目名称:Nancy.Redis,代码行数:26,代码来源:KeyValueStoreSessions.cs
示例15: Should_fail_to_create_xdocument_from_non_xml_body
public void Should_fail_to_create_xdocument_from_non_xml_body()
{
var context = new NancyContext() { Response = "hello" };
sut = new BrowserResponse(context, A.Fake<Browser>());
Assert.Throws<XmlException>(() => sut.BodyAsXml());
}
开发者ID:nclarence,项目名称:WebAPI.Testing,代码行数:7,代码来源:BrowserResponseExtensionsTests.cs
示例16: Handle
/// <summary>
/// Handle the error code
/// </summary>
/// <param name="statusCode">Status code</param>
/// <param name="context">The <see cref="NancyContext"/> instance of the current request.</param>
/// <returns>Nancy Response</returns>
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
if (context.Response != null && context.Response.Contents != null && !ReferenceEquals(context.Response.Contents, Response.NoBody))
{
return;
}
if (!this.errorMessages.ContainsKey(statusCode) || !this.errorPages.ContainsKey(statusCode))
{
return;
}
var result = new DefaultStatusCodeHandlerResult(statusCode, this.errorMessages[statusCode], StaticConfiguration.DisableErrorTraces ? DisableErrorTracesTrueMessage : context.GetExceptionDetails());
try
{
context.Response = this.responseNegotiator.NegotiateResponse(result, context);
context.Response.StatusCode = statusCode;
return;
}
catch (ViewNotFoundException)
{
// No view will be found for `DefaultStatusCodeHandlerResult`
// because it is rendered from embedded resources below
}
this.ModifyResponse(statusCode, context, result);
}
开发者ID:rahulchrty,项目名称:Nancy,代码行数:33,代码来源:DefaultStatusCodeHandler.cs
示例17: GetRollbarRequest
private static RollbarRequest GetRollbarRequest(NancyContext context) {
var rr = new RollbarRequest {
Url = context.Request.Url.ToString(),
Method = context.Request.Method,
Headers = context.Request.Headers.ToDictionary(x => x.Key, x => string.Join(",", x.Value)),
Params = ((IDictionary<string, object>)context.Parameters).ToDictionary(x => x.Key, x => x.Value),
UserIp = context.Request.UserHostAddress,
};
if (rr.Params.Count == 0) {
rr.Params = null;
}
if (rr.Method == "GET") {
rr.GetParams = ((IDictionary<string, object>) context.Request.Query).ToDictionary(x => x.Key, x => x.Value);
if (rr.GetParams.Count == 0) {
rr.GetParams = null;
}
}
if (rr.Method == "POST") {
rr.PostParams = ((IDictionary<string, object>) context.Request.Form)
.Concat((IDictionary<string, object>) context.Parameters)
.ToDictionary(x => x.Key, x => x.Value);
if (rr.PostParams.Count == 0) {
rr.PostParams = null;
}
rr.PostBody = context.Request.Body.AsString();
}
return rr;
}
开发者ID:l8nightcaffeine,项目名称:Nancy.Rollbar,代码行数:28,代码来源:RollbarDataFactory.cs
示例18: 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:RadifMasud,项目名称:Nancy,代码行数:31,代码来源:CachingBootstrapper.cs
示例19: ResolveMethodParameter
private object ResolveMethodParameter(ParameterInfo methodParameterInfo, IDictionary<string, object> queryParameters, NancyContext context)
{
if (IsQueryParameter(methodParameterInfo, queryParameters))
return GetValueFromQueryParameters(methodParameterInfo, queryParameters);
return GetValueFromRequestBody(methodParameterInfo, context);
}
开发者ID:MingLu8,项目名称:Nancy.WebApi,代码行数:7,代码来源:Extractors.cs
示例20: AddLinkHeaders
private static void AddLinkHeaders(NancyContext context, IEnumerable<Tuple<string, IEnumerable<Tuple<IResponseProcessor, ProcessorMatch>>>> compatibleHeaders, Response response)
{
var linkProcessors = new Dictionary<string, MediaRange>();
var compatibleHeaderMappings =
compatibleHeaders.SelectMany(m => m.Item2).SelectMany(p => p.Item1.ExtensionMappings);
foreach (var compatibleHeaderMapping in compatibleHeaderMappings)
{
if (!compatibleHeaderMapping.Item2.Matches(response.ContentType))
{
linkProcessors[compatibleHeaderMapping.Item1] = compatibleHeaderMapping.Item2;
}
}
if (!linkProcessors.Any())
{
return;
}
var baseUrl =
context.Request.Url.BasePath + "/" + Path.GetFileNameWithoutExtension(context.Request.Url.Path);
var links = linkProcessors.Keys
.Select(lp => string.Format("<{0}.{1}>; rel=\"{2}\"", baseUrl, lp, linkProcessors[lp]))
.Aggregate((lp1, lp2) => lp1 + "," + lp2);
response.Headers["Link"] = links;
}
开发者ID:pauloortins,项目名称:Nancy,代码行数:29,代码来源:DefaultRouteInvoker.cs
注:本文中的NancyContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论