本文整理汇总了C#中NancyContext类的典型用法代码示例。如果您正苦于以下问题:C# NancyContext类的具体用法?C# NancyContext怎么用?C# NancyContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
NancyContext类属于命名空间,在下文中一共展示了NancyContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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;
}
示例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);
}
示例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);
}
示例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;
}
示例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
};
}
示例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
};
}
示例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";
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
示例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);
}
示例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());
}