/// <summary> /// Deserialize the request body to a model /// </summary> /// <param name="mediaRange">Content type to deserialize</param> /// <param name="bodyStream">Request body stream</param> /// <param name="context">Current context</param> /// <returns>Model instance</returns> public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { if (bodyStream.CanSeek) { bodyStream.Position = 0; } var deserializedObject = this.serializer.Deserialize(new StreamReader(bodyStream), context.DestinationType); var properties = context.DestinationType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Select(p => new BindingMemberInfo(p)); var fields = context.DestinationType.GetFields(BindingFlags.Public | BindingFlags.Instance) .Select(f => new BindingMemberInfo(f)); if (properties.Concat(fields).Except(context.ValidModelBindingMembers).Any()) { return CreateObjectWithBlacklistExcluded(context, deserializedObject); } return deserializedObject; }
/// <summary> /// Deserialize the request body to a model /// </summary> /// <param name="mediaRange">Content type to deserialize</param> /// <param name="bodyStream">Request body stream</param> /// <param name="context">Current context</param> /// <returns>Model instance</returns> public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { if (bodyStream.CanSeek) { bodyStream.Position = 0; } var deserializedObject = ServiceStack.JsonSerializer.DeserializeFromStream(context.DestinationType, bodyStream); if (deserializedObject == null) { return null; } IEnumerable<BindingMemberInfo> properties; IEnumerable<BindingMemberInfo> fields; if (context.DestinationType.IsGenericType) { var genericType = context.DestinationType.GetGenericArguments().FirstOrDefault(); properties = genericType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => new BindingMemberInfo(p)); fields = genericType.GetFields(BindingFlags.Public | BindingFlags.Instance).Select(p => new BindingMemberInfo(p)); } else { properties = context.DestinationType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => new BindingMemberInfo(p)); fields = context.DestinationType.GetFields(BindingFlags.Public | BindingFlags.Instance) .Select(p => new BindingMemberInfo(p)); } return properties.Concat(fields).Except(context.ValidModelBindingMembers).Any() ? CreateObjectWithBlacklistExcluded(context, deserializedObject) : deserializedObject; }
/// <summary> /// Attempts to detect if the content type is ProtoBuffer. /// Supports: /// application/x-protobuf /// Matches are case insentitive to try and be as "accepting" as possible. /// </summary> /// <param name="mediaRange">Request content type</param> /// <returns>True if content type is JSON, false otherwise</returns> private static bool IsProtoBufType(MediaRange mediaRange) { if (string.IsNullOrWhiteSpace(mediaRange)) { return false; } try { if (mediaRange.Type.Matches(Constants.ProtoBufContentType)) { return true; } var subType = mediaRange.Subtype.ToString(); return (subType.StartsWith("vnd", StringComparison.OrdinalIgnoreCase) && subType.EndsWith("+x-protobuf", StringComparison.OrdinalIgnoreCase)); } catch (Exception) { return false; } }
/// <summary> /// Deserialize the request body to a model /// </summary> /// <param name="mediaRange">Content type to deserialize</param> /// <param name="bodyStream">Request body stream</param> /// <param name="context">Current <see cref="T:Nancy.ModelBinding.BindingContext" />.</param> /// <returns> /// Model instance /// </returns> public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { var yamlDeserializer = new Deserializer(); var reader = new StreamReader(bodyStream); // Tries to deserialize the request body to the type needed by the application code return(yamlDeserializer.Deserialize(reader, context.DestinationType)); }
public ProcessorMatch CanProcess(MediaRange mediaRange, dynamic model, NancyContext context) { return(new ProcessorMatch { ModelResult = MatchResult.DontCare, RequestedContentTypeResult = IsSuported(mediaRange) }); }
public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { using (var reader = new StreamReader(bodyStream)) { var deserializer = new Deserializer(); return(deserializer.Deserialize(reader, context.DestinationType)); } }
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return(new ProcessorMatch { ModelResult = MatchResult.DontCare, RequestedContentTypeResult = requestedMediaRange.Matches(MimeTypes.CanonicalMimeType) || requestedMediaRange.Matches("application/csv") ? MatchResult.ExactMatch : MatchResult.NoMatch, }); }
public override Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { var result = (IResult <T>)model; var responseBuilder = new ViewResponseResultVisitor <T>(this.viewFactory, context, this.viewName, this.ResponseDecorator); return(result.Accept(responseBuilder)); }
private object ModelUsedMultipleTimes(object arg) { var model = new NumericModel(10); return(Negotiate.WithModel(model) .WithMediaRangeModel(MediaRange.FromString("application/xml"), model) .WithMediaRangeModel(MediaRange.FromString("application/json"), model)); }
/// <summary> /// Process the response /// </summary> /// <param name="requestedMediaRange">Content type requested by the client</param> /// <param name="model">The model for the given media range</param> /// <param name="context">The nancy context</param> /// <returns>A response</returns> public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { if (!requestedMediaRange.Matches("application/ld+json")) { return(new JsonResponse(model, this.serializer, context.Environment)); } return(new JsonLdResponse(model, this.serializer, context.Environment)); }
private static IEnumerable <MediaRange> GetMediaRanges() { yield return(MediaRange.FromString("text/html")); yield return(MediaRange.FromString("application/json")); yield return(MediaRange.FromString("application/xml")); }
public void Should_handle_no_parameters_when_calling_tostring() { // Given var range = MediaRange.FromString("application/vnd.nancy"); // Then range.ToString().ShouldEqual("application/vnd.nancy"); }
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return(new ProcessorMatch { RequestedContentTypeResult = MatchResult.DontCare, ModelResult = MatchResult.DontCare }); }
public void Should_include_parameters_when_calling_tostring() { // Given var range = MediaRange.FromString("application/vnd.nancy;a=1;b=2"); // Then range.ToString().ShouldEqual("application/vnd.nancy;a=1;b=2"); }
public void Should_strip_whitespace_when_calling_tostring() { // Given var range = MediaRange.FromString("application/vnd.nancy ; a=1; b=2"); // Then range.ToString().ShouldEqual("application/vnd.nancy;a=1;b=2"); }
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { var apiResponse = new APIResponse(); apiResponse.Data = model; return(new JsonResponse(apiResponse, new DefaultJsonSerializer())); }
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { if (model is Stream) { return(new StreamResponse(() => model, requestedMediaRange)); } return(new ByteArrayResponse((byte[])model, requestedMediaRange)); }
public static BrowserResponse DeleteSecureJson(this Browser browser, string resource, object payload) { return(browser.Delete(resource, with => { with.HttpsRequest(); with.Accept(MediaRange.FromString("application/json")); with.JsonBody(payload); })); }
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return(new Response { ContentType = "application/json", Contents = stream => this.serializer.Serialize("application/json", model, stream), StatusCode = HttpStatusCode.OK }.WithHeader("Link", "</context.jsonld>; rel=\"http://www.w3.org/ns/json-ld#context\"; type=\"application/ld+json\"")); }
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { var match = new ProcessorMatch(); match.ModelResult = MatchResult.DontCare; match.RequestedContentTypeResult = MatchResult.ExactMatch; return(match); }
public void Should_match_with_parameters_if_parameters_match() { // Given var range1 = MediaRange.FromString("application/vnd.nancy;a=1;b=2"); var range2 = MediaRange.FromString("application/vnd.nancy;a=1;b=2"); // Then range1.MatchesWithParameters(range2).ShouldBeTrue(); }
private static MatchResult IsSuported(MediaRange mediaRange) { if (mediaRange.IsWildcard) { return(MatchResult.NoMatch); } return(MatchResult.NonExactMatch); }
/// <summary> /// Deserialize the request body to a model /// </summary> /// <param name="mediaRange">Content type to deserialize</param> /// <param name="bodyStream">Request body stream</param> /// <param name="context">Current context</param> /// <returns>Model instance</returns> public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { if (bodyStream.CanSeek) { bodyStream.Position = 0; } return RuntimeTypeModel.Default.Deserialize(bodyStream, null, context.DestinationType); }
/// <summary> /// Determines whether the processor can handle a given content type and model. /// </summary> /// <param name="requestedMediaRange">Content type requested by the client.</param> /// <param name="model">The model for the given media range.</param> /// <param name="context">The nancy context.</param> /// <returns> /// A <see cref="T:Nancy.Responses.Negotiation.ProcessorMatch" /> result that determines the priority of the processor. /// </returns> /// <exception cref="System.NotImplementedException"></exception> public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { // Tells Nancy that this processor can handle accept header values that end with "yaml" return(requestedMediaRange.Subtype.ToString().EndsWith("yaml") ? new ProcessorMatch { ModelResult = MatchResult.DontCare, RequestedContentTypeResult = MatchResult.NonExactMatch } : ProcessorMatch.None); }
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { var v1RouteList = CreateVersionedType((T)model); var r = requestedMediaRange.Subtype.ToString(); var formatter = _formats.First(f => r.Contains(f.Name)); return(formatter.Respond(v1RouteList, _serializers)); }
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return(new Response { Contents = stream => _serializer.Serialize(CustomContentType, model, stream), ContentType = CustomContentType, StatusCode = HttpStatusCode.OK }); }
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) => requestedMediaRange.Subtype.ToString().EndsWith("yaml") ? new ProcessorMatch { ModelResult = MatchResult.DontCare, RequestedContentTypeResult = MatchResult.NonExactMatch } : ProcessorMatch.None;
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="request"></param> /// <param name="status"></param> /// <param name="content"></param> /// <param name="contentType"></param> public IOResponse(IORequest request, IOStatus status, Stream content, MediaRange contentType) : this(request, status) { Contract.Requires <ArgumentNullException>(request != null); Contract.Requires <ArgumentNullException>(content != null); this.content = content; this.contentType = contentType; }
public void TestPostSparql() { TestSparqlPostSucceeds("foo", SparqlQueryString, null, null, SparqlXml, SparqlResultsFormat.Xml, null); TestSparqlPostSucceeds("foo", SparqlQueryString, new[] { "http://some/graph/uri" }, null, MediaRange.FromString("application/sparql-results+xml"), SparqlResultsFormat.Xml, null); TestSparqlPostSucceeds("foo", SparqlQueryString, new[] { "http://some/graph/uri", "http://some/other/uri" }, null, MediaRange.FromString("application/sparql-results+xml"), SparqlResultsFormat.Xml, null); }
/// <summary> /// Deserialize the request body to a model /// </summary> /// <param name="mediaRange">Content type to deserialize</param> /// <param name="bodyStream">Request body stream</param> /// <param name="context">Current context</param> /// <returns>Model instance</returns> public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context) { if (bodyStream.CanSeek) { bodyStream.Position = 0; } return(RuntimeTypeModel.Default.Deserialize(bodyStream, null, context.DestinationType)); }
private static bool IsExactJsonContentType(MediaRange requestedContentType) { if (requestedContentType.Type.IsWildcard && requestedContentType.Subtype.IsWildcard) { return(true); } return(requestedContentType.Matches("application/json") || requestedContentType.Matches("text/json")); }
public void Should_match_with_parameters_if_parameters_match_in_any_order() { // Given var range1 = new MediaRange("application/vnd.nancy;a=1;b=2"); var range2 = new MediaRange("application/vnd.nancy;b=2;a=1"); // Then range1.MatchesWithParameters(range2).ShouldBeTrue(); }
public void Should_not_match_with_parameters_if_parameters_do_not_match() { // Given var range1 = new MediaRange("application/vnd.nancy;a=1;b=2"); var range2 = new MediaRange("application/vnd.nancy;a=1;b=2;c=3"); // Then range1.MatchesWithParameters(range2).ShouldBeFalse(); }
public void TestGetReturnsHtmlForm() { var brightstar = new Mock <IBrightstarService>(); var app = new Browser(new FakeNancyBootstrapper(brightstar.Object)); var response = app.Get("/foo/update", with => with.Accept(MediaRange.FromString("text/html"))); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(response.Body.AsString(), Contains.Substring("<title>BrightstarDB: SPARQL Update</title>")); }
private static Response SafeInvokeResponseProcessor(IResponseProcessor responseProcessor, MediaRange mediaRange, object model, NancyContext context) { try { return responseProcessor.Process(mediaRange, model, context); } catch (Exception e) { context.WriteTraceLog(sb => sb.AppendFormat("[DefaultRouteInvoker] Processor threw {0} exception: {1}", e.GetType(), e.Message)); } return null; }
/// <summary> /// Whether the deserializer can deserialize the content type /// </summary> /// <param name="mediaRange">Content type to deserialize</param> /// <param name="context">Current <see cref="BindingContext"/>.</param> /// <returns>True if supported, false otherwise</returns> public bool CanDeserialize(MediaRange mediaRange, BindingContext context) { return IsProtoBufType(mediaRange); }
/// <summary> /// Whether the deserializer can deserialize the content type /// </summary> /// <param name="mediaRange">Content type to deserialize</param> /// <param name="context">Current <see cref="BindingContext"/>.</param> /// <returns>True if supported, false otherwise</returns> public bool CanDeserialize(MediaRange mediaRange, BindingContext context) { return Helpers.IsJsonType(mediaRange); }