示例#1
0
        public void SetContentTypeTest()
        {
            settings.SetContentType("application/xml", null);
            ODataMessageWriterSettings copyOfSettings = settings.Clone();

            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Equal("application/xml", settings.AcceptableMediaTypes);
            Assert.Equal("application/xml", copyOfSettings.AcceptableMediaTypes);
            Assert.Null(settings.AcceptableCharsets);
            Assert.Null(copyOfSettings.AcceptableCharsets);

            settings.SetContentType("application/json", "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Equal("application/json", settings.AcceptableMediaTypes);
            Assert.Equal("application/json", copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);

            settings.SetContentType(null, "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Null(settings.AcceptableMediaTypes);
            Assert.Null(copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);

            settings.SetContentType(string.Empty, "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Empty(settings.AcceptableMediaTypes);
            Assert.Empty(copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);

            settings.SetContentType("json", "utf8");
            copyOfSettings = settings.Clone();
            Assert.Null(settings.Format);
            Assert.Null(copyOfSettings.Format);
            Assert.Equal("application/json", settings.AcceptableMediaTypes);
            Assert.Equal("application/json", copyOfSettings.AcceptableMediaTypes);
            Assert.Equal("utf8", settings.AcceptableCharsets);
            Assert.Equal("utf8", copyOfSettings.AcceptableCharsets);
        }
        public void SetContentTypeTest()
        {
            settings.SetContentType("application/xml", null);
            ODataMessageWriterSettings copyOfSettings = settings.Clone();

            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().Be("application/xml");
            copyOfSettings.AcceptableMediaTypes.Should().Be("application/xml");
            settings.AcceptableCharsets.Should().BeNull();
            copyOfSettings.AcceptableCharsets.Should().BeNull();

            settings.SetContentType("application/json", "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().Be("application/json");
            copyOfSettings.AcceptableMediaTypes.Should().Be("application/json");
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");

            settings.SetContentType(null, "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().BeNull();
            copyOfSettings.AcceptableMediaTypes.Should().BeNull();
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");

            settings.SetContentType(string.Empty, "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().BeEmpty();
            copyOfSettings.AcceptableMediaTypes.Should().BeEmpty();
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");

            settings.SetContentType("json", "utf8");
            copyOfSettings = settings.Clone();
            settings.Format.Should().BeNull();
            copyOfSettings.Format.Should().BeNull();
            settings.AcceptableMediaTypes.Should().Be("application/json");
            copyOfSettings.AcceptableMediaTypes.Should().Be("application/json");
            settings.AcceptableCharsets.Should().Be("utf8");
            copyOfSettings.AcceptableCharsets.Should().Be("utf8");
        }
示例#3
0
        private Action <WriterTestConfiguration> WriteServiceDocument(Func <XElement, XElement> fragmentExtractor, string expectedXml)
        {
            var sampleWorkspace = ObjectModelUtils.CreateDefaultWorkspace();

            return((testConfiguration) =>
            {
                if (testConfiguration.IsRequest)
                {
                    return;
                }

                ODataMessageWriterSettings actualSettings = testConfiguration.MessageWriterSettings;
                if (actualSettings.PayloadBaseUri == null)
                {
                    actualSettings = actualSettings.Clone();
                    actualSettings.PayloadBaseUri = new Uri("http://odata.org");
                }

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    new PayloadWriterTestDescriptor <ODataServiceDocument>(this.Settings, sampleWorkspace, expectedXml, null, fragmentExtractor, null, /*disableXmlNamespaceNormalization*/ true),
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(sampleWorkspace),
                    this.Assert,
                    actualSettings,
                    baselineLogger: this.Logger);
            });
        }
示例#4
0
        private void WriteResponseBody(OutputFormatterWriteContext context)
        {
            HttpContext  httpContext = context.HttpContext;
            HttpRequest  request     = context.HttpContext.Request;
            HttpResponse response    = context.HttpContext.Response;

            IEdmModel model = context.HttpContext.ODataFeature().Model;

            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
            }

            object value        = null;
            object graph        = null;
            var    objectResult = context.Object as PageResult <object>;

            if (objectResult != null)
            {
                value = objectResult.Items;
                graph = objectResult;
            }
            else
            {
                value = context.Object;
                graph = value;
            }
            var type = value.GetType();

            ODataSerializer serializer = GetSerializer(type, value, context);

            IUrlHelper urlHelper = context.HttpContext.UrlHelper();

            ODataPath            path = httpContext.ODataFeature().Path;
            IEdmNavigationSource targetNavigationSource = path == null ? null : path.NavigationSource;

            string preferHeader     = RequestPreferenceHelpers.GetRequestPreferHeader(request);
            string annotationFilter = null;

            if (!String.IsNullOrEmpty(preferHeader))
            {
                ODataMessageWrapper messageWrapper = new ODataMessageWrapper(response.Body, response.Headers);
                messageWrapper.SetHeader(RequestPreferenceHelpers.PreferHeaderName, preferHeader);
                annotationFilter = messageWrapper.PreferHeader().AnnotationFilter;
            }

            IODataResponseMessage responseMessage = new ODataMessageWrapper(response.Body, response.Headers);

            if (annotationFilter != null)
            {
                responseMessage.PreferenceAppliedHeader().AnnotationFilter = annotationFilter;
            }

            Uri baseAddress = GetBaseAddress(request);
            ODataMessageWriterSettings writerSettings = _messageWriterSettings.Clone();

            writerSettings.BaseUri     = baseAddress;
            writerSettings.Version     = ODataVersion.V4;
            writerSettings.Validations = writerSettings.Validations & ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;

            string metadataLink = urlHelper.CreateODataLink(request, MetadataSegment.Instance);

            if (metadataLink == null)
            {
                throw new SerializationException(SRResources.UnableToDetermineMetadataUrl);
            }

            writerSettings.ODataUri = new ODataUri
            {
                ServiceRoot = baseAddress,

                // TODO: 1604 Convert webapi.odata's ODataPath to ODL's ODataPath, or use ODL's ODataPath.
                SelectAndExpand = httpContext.ODataFeature().SelectExpandClause,
                Path            = (path == null) ? null : path.ODLPath
                                  //Path = (path == null || IsOperationPath(path)) ? null : path.ODLPath,
            };

            using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model))
            {
                ODataSerializerContext writeContext = new ODataSerializerContext()
                {
                    Context          = context.HttpContext,
                    Url              = urlHelper,
                    NavigationSource = targetNavigationSource,
                    Model            = model,
                    RootElementName  = GetRootElementName(path) ?? "root",
                    SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.ResourceSet,
                    Path               = path,
                    MetadataLevel      = ODataMediaTypes.GetMetadataLevel(MediaTypeHeaderValue.Parse(context.ContentType.Value)),
                    SelectExpandClause = request.ODataFeature().SelectExpandClause,
                };

                serializer.WriteObject(graph, type, messageWriter, writeContext);
            }
        }
        private void WriteResponseBody(OutputFormatterWriteContext context)
        {
            HttpContext  httpContext = context.HttpContext;
            HttpRequest  request     = context.HttpContext.Request;
            HttpResponse response    = context.HttpContext.Response;

            IEdmModel model = context.HttpContext.ODataFeature().Model;

            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
            }

            object value        = null;
            object graph        = null;
            var    objectResult = context.Object as PageResult <object>;

            if (objectResult != null)
            {
                value = objectResult.Items;
                graph = objectResult;
            }
            else
            {
                value = context.Object;
                graph = value;
            }
            var type = value.GetType();

            ODataSerializer serializer = GetSerializer(type, value, context);

            IUrlHelper urlHelper = context.HttpContext.UrlHelper();

            ODataPath            path = httpContext.ODataFeature().Path;
            IEdmNavigationSource targetNavigationSource = path == null ? null : path.NavigationSource;

            string preferHeader     = RequestPreferenceHelpers.GetRequestPreferHeader(request);
            string annotationFilter = null;

            if (!String.IsNullOrEmpty(preferHeader))
            {
                ODataMessageWrapper messageWrapper = new ODataMessageWrapper(response.Body, response.Headers);
                messageWrapper.SetHeader(RequestPreferenceHelpers.PreferHeaderName, preferHeader);
                annotationFilter = messageWrapper.PreferHeader().AnnotationFilter;
            }

            IODataResponseMessage responseMessage = new ODataMessageWrapper(response.Body, response.Headers);

            if (annotationFilter != null)
            {
                responseMessage.PreferenceAppliedHeader().AnnotationFilter = annotationFilter;
            }

            Uri baseAddress = GetBaseAddress(request);
            ODataMessageWriterSettings writerSettings = _messageWriterSettings.Clone();

            writerSettings.BaseUri     = baseAddress;
            writerSettings.Version     = ODataVersion.V4;
            writerSettings.Validations = writerSettings.Validations & ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;

            string metadataLink = urlHelper.CreateODataLink(request, MetadataSegment.Instance);

            if (metadataLink == null)
            {
                throw new SerializationException(SRResources.UnableToDetermineMetadataUrl);
            }

            writerSettings.ODataUri = new ODataUri
            {
                ServiceRoot = baseAddress,

                // TODO: 1604 Convert webapi.odata's ODataPath to ODL's ODataPath, or use ODL's ODataPath.
                SelectAndExpand = httpContext.ODataFeature().SelectExpandClause,
                Path            = (path == null) ? null : path.ODLPath
                                  //Path = (path == null || IsOperationPath(path)) ? null : path.ODLPath,
            };

            #region 为OData添加缓存  使用的EF二级缓存 这里是先从缓存获取数据
            //var queryResult = graph as IQueryable;
            //PageResult<object> target = null;
            //if (queryResult == null)
            //{
            //    target = graph as PageResult<object>;
            //    if (target != null) queryResult = target.Items.AsQueryable();
            //}
            //var isReadCache = queryResult != null || target != null;

            //var cacheValue = isReadCache?queryResult.CacheResult(context.HttpContext.RequestServices):null;

            //if (isReadCache&&target != null && cacheValue != null)
            //{
            //    var pageResult = cacheValue as IEnumerable<object>;
            //    //long? count = target.Count.HasValue ? (long?)pageResult.LongCount() : null;
            //    cacheValue = new PageResult<object>(pageResult, null, target.Count);
            //}

            //if (isReadCache&&cacheValue != null) graph = cacheValue;

            #endregion

            using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model))
            {
                ODataSerializerContext writeContext = new ODataSerializerContext()
                {
                    Context          = context.HttpContext,
                    Url              = urlHelper,
                    NavigationSource = targetNavigationSource,
                    Model            = model,
                    RootElementName  = GetRootElementName(path) ?? "root",
                    SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.ResourceSet,
                    Path               = path,
                    MetadataLevel      = ODataMediaTypes.GetMetadataLevel(MediaTypeHeaderValue.Parse(context.ContentType.Value)),
                    SelectExpandClause = request.ODataFeature().SelectExpandClause,
                };

                serializer.WriteObject(graph, type, messageWriter, writeContext);

                #region 这里是往缓存中 存储数据
                //if (isReadCache&&cacheValue == null)
                //{
                //    writeContext.Context.Response.Body.Position = 0;
                //    StreamReader reder = new StreamReader(writeContext.Context.Response.Body);
                //    var bodyStr = reder.ReadToEnd();
                //    JObject.Parse(bodyStr).TryGetValue("value",out JToken values);
                //    cacheValue = values.ToObject(type.MarkListType());

                //    queryResult.CacheQuerable(cacheValue, writeContext.Context.RequestServices);
                //}
                #endregion
            }
        }