// https://forums.asp.net/t/1773007.aspx?How+to+correctly+use+PostAsync+and+PutAsync+
        public string Put <T>(T data)
        {
            System.Net.Http.Headers.MediaTypeHeaderValue mediaType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            Newtonsoft.Json.JsonSerializerSettings       jsonSerializerSettings =
                new Newtonsoft.Json.JsonSerializerSettings();

            // JsonNetFormatter jsonFormatter = new JsonNetFormatter(jsonSerializerSettings);
            // var requestMessage = new
            // System.Net.Http.HttpRequestMessage<T>(data, mediaType
            // , new System.Net.Http.Formatting.MediaTypeFormatter[] { jsonFormatter });

            System.Net.Http.ObjectContent content = new System.Net.Http.ObjectContent <T>(data
                                                                                          , new System.Net.Http.Formatting.JsonMediaTypeFormatter()
                                                                                          );

            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                string _endpoint = "";
                httpClient.PutAsync(_endpoint, content).ContinueWith(httpResponseMessage =>
                {
                    return(httpResponseMessage.Result.Content.ReadAsStringAsync());
                    // return await Task.Run(() => httpResponseMessage.Result.Content.ReadAsStringAsync());
                });
            }

            return(null);
        }
Beispiel #2
0
 public WebApiRequestException(string message, System.Net.HttpStatusCode statusCode, string response, System.Net.Http.Headers.HttpResponseHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue contentType) : base(message)
 {
     StatusCode  = statusCode;
     Response    = response;
     Headers     = headers;
     ContentType = contentType;
 }
        public async System.Threading.Tasks.Task <string> Put <T>(string uri, T data)
        {
            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                System.Net.Http.Headers.MediaTypeHeaderValue mediaType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                Newtonsoft.Json.JsonSerializerSettings       jsonSerializerSettings =
                    new Newtonsoft.Json.JsonSerializerSettings();

                JsonNetFormatter jsonFormatter = new JsonNetFormatter(jsonSerializerSettings);

                System.Net.Http.ObjectContent content = new System.Net.Http.ObjectContent <T>(data
                                                                                              , new System.Net.Http.Formatting.JsonMediaTypeFormatter()
                                                                                              );

                System.Net.Http.HttpResponseMessage response = await httpClient.PutAsync(uri, content);

                response.EnsureSuccessStatusCode();
                return(response.Content.ReadAsStringAsync().Result);

                /*
                 * var requestMessage = new System.Net.Http.HttpRequestMessage
                 *  (data, mediaType, new System.Net.Http.Formatting.MediaTypeFormatter[] { jsonFormatter });
                 *
                 * // var result = httpClient.PutAsync("_endpoint", requestMessage.Content).Result;
                 * // return result.Content.ReadAsStringAsync().Result;
                 */
            }
        }
Beispiel #4
0
        public static Encoding GetEncoding(System.Net.Http.Headers.MediaTypeHeaderValue mediaTypeHeaderValue)
        {
            string charset = mediaTypeHeaderValue?.CharSet;

            // If we do have encoding information in the 'Content-Type' header, use that information to convert
            // the content to a string.
            if (charset != null)
            {
                try
                {
                    // Remove at most a single set of quotes.
                    if (charset.Length > 2 &&
                        charset[0] == '\"' &&
                        charset[charset.Length - 1] == '\"')
                    {
                        return(Encoding.GetEncoding(charset.Substring(1, charset.Length - 2)));
                    }
                    else
                    {
                        return(Encoding.GetEncoding(charset));
                    }
                }
                catch (ArgumentException e)
                {
                    throw new InvalidOperationException("The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.", e);
                }
            }
            return(null);
        }
Beispiel #5
0
        private static HttpRequestMessage CreateHttpRequestMessage(string uri, Stream requestStream, HttpMethod method,
                                                                   IHeaderDictionary customHeaders, ILogger log)
        {
            //Default to JSON content type
            HttpContent content = null;

            if (requestStream != null)
            {
                const string DEFAULT_CONTENT_TYPE = ContentTypeConstants.ApplicationJson;

                var contentType = MediaTypeHeaderValue.Parse(DEFAULT_CONTENT_TYPE);
                if (customHeaders?.ContainsKey(HeaderNames.ContentType) == true)
                {
                    if (MediaTypeHeaderValue.TryParse(customHeaders[HeaderNames.ContentType], out var ct))
                    {
                        contentType = ct;
                    }
                    else
                    {
                        log.LogWarning($"Failed to convert {customHeaders[HeaderNames.ContentType]} to a valid Content-Type.");
                    }
                }
                // The content coming in with already be encoded correctly (for strings, via Encoding.UTF8.GetBytes())
                content = new StreamContent(requestStream);
                content.Headers.ContentType = contentType;
            }

            return(new HttpRequestMessage(method, uri)
            {
                Content = content
            });
        }
        public async void ProcessRequest(Microsoft.AspNetCore.Http.HttpContext context)
#endif
        {
            var request  = context.Request;
            var response = context.Response;

            string result;

            try
            {
                result = this.DoCommand(context);
            }
            catch (System.Exception ex)
            {
                result = System.Text.Json.JsonSerializer.Serialize(new Thinksea.Net.FileUploader.Result()
                {
                    ErrorCode = 1,
                    Message   = ex.Message
                });
#if DEBUG
                System.Diagnostics.Debug.WriteLine(ex.ToString());
#endif
            }

#if NETFRAMEWORK
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.ContentType     = "application/json";
            response.AddHeader("Pragma", "no-cache");
            response.CacheControl = "no-cache";
            response.Write(result);
#elif NETCOREAPP
            {
                if (!response.Headers.ContainsKey(Microsoft.Net.Http.Headers.HeaderNames.Pragma))
                {
                    response.Headers.Add(Microsoft.Net.Http.Headers.HeaderNames.Pragma, "no-cache");
                }
                //response.CacheControl = "no-store";
                if (!response.Headers.ContainsKey(Microsoft.Net.Http.Headers.HeaderNames.CacheControl))
                {
                    response.Headers.Add(Microsoft.Net.Http.Headers.HeaderNames.CacheControl, "no-cache");
                }

                System.Net.Http.Headers.MediaTypeHeaderValue mediaType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                mediaType.CharSet    = "utf-8";
                response.ContentType = mediaType.ToString();
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(ms, System.Text.Encoding.UTF8))
                    {
                        sw.Write(result);
                        sw.Flush();
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
                        await ms.CopyToAsync(response.Body);
                    }
                }
                return;
            }
#endif
        }
Beispiel #7
0
 public MediaTypeHeaderValue(System.Net.Http.Headers.MediaTypeHeaderValue containedObject)
 {
     if ((containedObject == null))
     {
         throw new System.ArgumentNullException("containedObject");
     }
     this.containedObject = containedObject;
 }
        /// <inheritdoc/>
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            Type type = context.ObjectType;

            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            type = TypeHelper.GetTaskInnerTypeOrSelf(type);

            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpResponse response = context.HttpContext.Response;

            if (typeof(Stream).IsAssignableFrom(type))
            {
                // Ideally, it should go into the "ODataRawValueSerializer",
                // However, OData lib doesn't provide the method to overwrite/copyto stream
                // So, Here's the workaround
                Stream objStream = context.Object as Stream;
                return(CopyStreamAsync(objStream, response));
            }

            Uri baseAddress = GetBaseAddressInternal(request);
            MediaTypeHeaderValue contentType = GetContentType(response.Headers[HeaderNames.ContentType].FirstOrDefault());

            Func <ODataSerializerContext> getODataSerializerContext = () =>
            {
                return(new ODataSerializerContext()
                {
                    Request = request,
                });
            };

            ODataSerializerProvider serializerProvider = request.GetRequestContainer().GetRequiredService <ODataSerializerProvider>();

            return(ODataOutputFormatterHelper.WriteToStreamAsync(
                       type,
                       context.Object,
                       request.GetModel(),
                       ResultHelpers.GetODataResponseVersion(request),
                       baseAddress,
                       contentType,
                       new WebApiUrlHelper(request.GetUrlHelper()),
                       new WebApiRequestMessage(request),
                       new WebApiRequestHeaders(request.Headers),
                       (services) => ODataMessageWrapperHelper.Create(new StreamWrapper(response.Body), response.Headers, services),
                       (edmType) => serializerProvider.GetEdmTypeSerializer(edmType),
                       (objectType) => serializerProvider.GetODataPayloadSerializer(objectType, request),
                       getODataSerializerContext));
        }
Beispiel #9
0
 public Response HasContentType(Http.Headers.MediaTypeHeaderValue contentType)
 {
     return(new Response(this.response.Then(response => {
         Assert.Equal(contentType, response.Content.Headers.ContentType);
         return response;
     }))
     {
         DefaultStatus = this.DefaultStatus
     });
 }
        public ProtobufSerializer(Func <RuntimeTypeModel, RuntimeTypeModel> serializerConfigurator)
        {
            if (serializerConfigurator == null)
            {
                throw new ArgumentNullException(nameof(serializerConfigurator));
            }
            _runtimeTypeModel = serializerConfigurator(TypeModel.Create());

            MediaType = MediaTypeHeaderValue.Parse("application/x-protobuf");
        }
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            Type type = context.ObjectType;

            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            type = TypeHelper.GetTaskInnerTypeOrSelf(type);

            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            try
            {
                HttpResponse         response    = context.HttpContext.Response;
                Uri                  baseAddress = GetBaseAddressInternal(request);
                MediaTypeHeaderValue contentType = GetContentType(response.Headers[HeaderNames.ContentType].FirstOrDefault());

                Func <ODataSerializerContext> getODataSerializerContext = () =>
                {
                    return(new ODataSerializerContext()
                    {
                        Request = request,
                    });
                };

                ODataSerializerProvider serializerProvider = request.GetRequestContainer().GetRequiredService <ODataSerializerProvider>();

                ODataOutputFormatterHelper.WriteToStream(
                    type,
                    context.Object,
                    request.GetModel(),
                    ResultHelpers.GetODataResponseVersion(request),
                    baseAddress,
                    contentType,
                    new WebApiUrlHelper(request.GetUrlHelper()),
                    new WebApiRequestMessage(request),
                    new WebApiRequestHeaders(request.Headers),
                    (services) => ODataMessageWrapperHelper.Create(response.Body, response.Headers, services),
                    (edmType) => serializerProvider.GetEdmTypeSerializer(edmType),
                    (objectType) => serializerProvider.GetODataPayloadSerializer(objectType, request),
                    getODataSerializerContext);

                return(TaskHelpers.Completed());
            }
            catch (Exception ex)
            {
                return(TaskHelpers.FromError(ex));
            }
        }
Beispiel #12
0
        /// <inheritdoc/>
        public override void WriteResponseHeaders(OutputFormatterWriteContext context)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            Type type = context.ObjectType;

            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            type = TypeHelper.GetTaskInnerTypeOrSelf(type);

            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpResponse response = context.HttpContext.Response;

            response.ContentType = context.ContentType.Value;

            MediaTypeHeaderValue contentType = GetContentType(response.Headers[HeaderNames.ContentType].FirstOrDefault());

            // Determine the content type.
            MediaTypeHeaderValue newMediaType = null;

            if (ODataOutputFormatterHelper.TryGetContentHeader(type, contentType, out newMediaType))
            {
                response.Headers[HeaderNames.ContentType] = new StringValues(newMediaType.ToString());
            }

            // Set the character set.
            MediaTypeHeaderValue currentContentType = GetContentType(response.Headers[HeaderNames.ContentType].FirstOrDefault());
            RequestHeaders       requestHeader      = request.GetTypedHeaders();

            if (requestHeader != null && requestHeader.AcceptCharset != null)
            {
                IEnumerable <string> acceptCharsetValues = requestHeader.AcceptCharset.Select(cs => cs.Value.Value);

                string newCharSet = string.Empty;
                if (ODataOutputFormatterHelper.TryGetCharSet(currentContentType, acceptCharsetValues, out newCharSet))
                {
                    currentContentType.CharSet = newCharSet;
                    response.Headers[HeaderNames.ContentType] = new StringValues(currentContentType.ToString());
                }
            }

            // Add version header.
            response.Headers[ODataVersionConstraint.ODataServiceVersionHeader] = ODataUtils.ODataVersionToString(ResultHelpers.GetODataResponseVersion(request));
        }
        internal static void SetFileSettings(string fileName, HttpResponseMessage response, String contentType)
        {
            var mt  = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
            var con = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName
            };

            response.Content.Headers.ContentType        = mt;
            response.Content.Headers.ContentDisposition = con;
        }
Beispiel #14
0
        private MediaTypeHeaderValue GetContentType(string contentTypeValue)
        {
            MediaTypeHeaderValue contentType = null;

            if (!string.IsNullOrEmpty(contentTypeValue))
            {
                MediaTypeHeaderValue.TryParse(contentTypeValue, out contentType);
            }

            return(contentType);
        }
Beispiel #15
0
        public static async Task <IHttpResponse> CreateContentFormAsync(
            [Property(Name = ContentIdPropertyName)] Guid contentId,
            [Property(Name = ContentPropertyName)] byte[] contentBytes,
            [Header(Content = ContentPropertyName)] System.Net.Http.Headers.MediaTypeHeaderValue mediaHeader,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists)
        {
            var contentType = mediaHeader.MediaType;

            return(await EastFive.Api.Azure.Content.CreateContentAsync(contentId, contentType, contentBytes,
                                                                       () => onCreated(),
                                                                       () => onAlreadyExists()));
        }
Beispiel #16
0
        public async Task <HttpResponseMessage> RunResetAccountForm(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "auth/reset")] HttpRequest req,
            ExecutionContext context,
            ILogger log)
        {
            log.LogInformation($"#auth #reset");
            string filePath = Path.Combine(context.FunctionDirectory, "../Templates/ResetPasswordForm.html");

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            var stream   = new FileStream(filePath, FileMode.Open);

            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/html");
            return(response);
        }
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Content != null && !string.IsNullOrEmpty(_options.RequestContentType))
            {
                request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(_options.RequestContentType);
            }

            await SignRequest(request);

            var response = await base.SendAsync(request, cancellationToken);

            ValidateResponse(response);

            return(response);
        }
Beispiel #18
0
        public HttpResponseMessage Download(string fileType, string folder)
        {
            var fullPath         = Path.Combine(Config.Configuration.WorkingDirectory, "Editor", folder);
            var downloadFileName = "document.pdf";
            var documentFileName = Path.Combine(Config.Configuration.WorkingDirectory, "Editor", folder, downloadFileName);
            var contentType      = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

            switch (fileType)
            {
            case "docx":
                downloadFileName = "document.docx";
                contentType      = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                break;

            case "svg":
                downloadFileName = "document.svg";
                contentType      = new System.Net.Http.Headers.MediaTypeHeaderValue("image/svg+xml");
                break;

            case "xps":
                downloadFileName = "document.xps";
                contentType      = new System.Net.Http.Headers.MediaTypeHeaderValue("application/oxps, application/vnd.ms-xpsdocument");
                break;

            case "xls":
                downloadFileName = "document.xlsx";
                contentType      = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                break;

            case "html":
                downloadFileName = "document.html";
                contentType      = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
                break;
            }
            documentFileName = string.Format("{0}\\{1}", fullPath, downloadFileName);
            var dataBytes  = File.ReadAllBytes(documentFileName);
            var dataStream = new MemoryStream(dataBytes);

            HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);

            httpResponseMessage.Content = new StreamContent(dataStream);
            httpResponseMessage.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            httpResponseMessage.Content.Headers.ContentDisposition.FileName = downloadFileName;
            httpResponseMessage.Content.Headers.ContentType = contentType;
            return(httpResponseMessage);
        }
Beispiel #19
0
        public AcceptHeaderAttribute(string contentType, params string[] otherContentTypes)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            // We want to ensure that the given provided content types are valid values, so
            // we validate them using the semantics of MediaTypeHeaderValue.
            MediaTypeHeaderValue.Parse(contentType);

            for (var i = 0; i < otherContentTypes.Length; i++)
            {
                MediaTypeHeaderValue.Parse(otherContentTypes[i]);
            }

            ContentTypes = GetContentTypes(contentType, otherContentTypes);
        }
Beispiel #20
0
        static Http.Headers.MediaTypeHeaderValue GetContentType(string path)
        {
            Http.Headers.MediaTypeHeaderValue result;
            switch (path.Split(new [] { "." }, StringSplitOptions.RemoveEmptyEntries).Last())
            {
            default: result = null; break;

            case "json": result = new Http.Headers.MediaTypeHeaderValue("application/json")
            {
                    CharSet = "utf-8"
            }; break;

            case "txt": result = new Http.Headers.MediaTypeHeaderValue("text/plain")
            {
                    CharSet = "utf-8"
            }; break;
            }
            return(result);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        /// <param name="context"></param>
        /// <param name="connection"></param>
        /// <returns></returns>
        public async Task ProcessResponse(MsgHandlerEventArgs args, HttpContext context, IConnection connection)
        {
            if (args.Message.Reply != null)
            {
                _log.LogTrace($"Create response to reply {args.Message.Reply}");

                if (context.Response.Body.CanSeek)
                {
                    context.Response.Body.Position = 0;
                }

                var response = new HttpResponseMessage
                {
                    StatusCode = (HttpStatusCode)context.Response.StatusCode,
                    Content    = new StreamContent(context.Response.Body),
                };

                response.Content.Headers.ContentType   = MediaTypeHeaderValue.Parse(context.Response.ContentType);
                response.Content.Headers.ContentLength = context.Response.Body.Length;

                foreach (var header in context.Response.Headers)
                {
                    response.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable());
                }

                var content = new HttpMessageContent(response);
                var bytes   = await content.ReadAsByteArrayAsync();

                _log.LogTrace($"Send response to reply {args.Message.Reply}");
                connection.Publish(args.Message.Reply, bytes);
                _log.LogTrace($"Response to reply {args.Message.Reply} sended");
            }
            else
            {
                _log.LogTrace($"reply is empty, response not be sended. request url {context.Request.GetDisplayUrl()}");
            }
        }
Beispiel #22
0
 /// <summary>
 /// Define os cabeçalhos de conteúdo padrão.
 /// </summary>
 /// <param name="type"></param>
 /// <param name="headers"></param>
 /// <param name="mediaType"></param>
 public override void SetDefaultContentHeaders(System.Type type, System.Net.Http.Headers.HttpContentHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
 {
     base.SetDefaultContentHeaders(type, headers, mediaType);
     headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
 }
        /// <summary>
        /// Returns a specialized instance of the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" /> that can format a response for the given parameters.
        /// </summary>
        /// <param name="type">The type to format.</param>
        /// <param name="request">The request.</param>
        /// <param name="mediaType">The media type.</param>
        /// <returns>
        /// Returns <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" />.
        /// </returns>
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            var    qryParams      = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query);
            string loadAttributes = qryParams["LoadAttributes"] ?? string.Empty;

            // if "simple" or True is specified in the LoadAttributes param, tell the formatter to serialize in Simple mode
            SerializeInSimpleMode = loadAttributes.Equals("simple", StringComparison.OrdinalIgnoreCase) || (loadAttributes.AsBooleanOrNull() ?? false);

            // if either "simple", "expanded", or True is specified in the LoadAttributes param, tell the formatter to load the attributes on the way out
            LoadAttributes = SerializeInSimpleMode || loadAttributes.Equals("expanded", StringComparison.OrdinalIgnoreCase);

            return(base.GetPerRequestFormatterInstance(type, request, mediaType));
        }
        /// <summary>
        /// Returns a specialized instance of the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" /> that can format a response for the given parameters.
        /// </summary>
        /// <param name="type">The type to format.</param>
        /// <param name="request">The request.</param>
        /// <param name="mediaType">The media type.</param>
        /// <returns>
        /// Returns <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" />.
        /// </returns>
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            var    qryParams      = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query);
            string loadAttributes = qryParams["LoadAttributes"] ?? string.Empty;

            string[] limitToAttributeKeyList = qryParams["AttributeKeys"]?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim()).ToArray();

            // if "simple" or True is specified in the LoadAttributes param, tell the formatter to serialize in Simple mode
            bool serializeInSimpleMode = loadAttributes.Equals("simple", StringComparison.OrdinalIgnoreCase) || (loadAttributes.AsBooleanOrNull() ?? false);

            // if either "simple", "expanded", or True is specified in the LoadAttributes param, tell the formatter to load the attributes on the way out
            bool loadAttributesEnabled = serializeInSimpleMode || loadAttributes.Equals("expanded", StringComparison.OrdinalIgnoreCase);

            Rock.Model.Person person = null;

            // NOTE: request.Properties["Person"] gets set in Rock.Rest.Filters.SecurityAttribute.OnActionExecuting
            if (loadAttributesEnabled && request.Properties.ContainsKey("Person"))
            {
                person = request.Properties["Person"] as Rock.Model.Person;
            }

            // store the request options in HttpContext.Current.Items so they are thread safe, and only for this request
            var loadAttributesOptions = new LoadAttributesOptions(loadAttributesEnabled, serializeInSimpleMode, limitToAttributeKeyList, person);

            HttpContext.Current.Items[LoadAttributesOptions.ContextItemsKey] = loadAttributesOptions;

            return(base.GetPerRequestFormatterInstance(type, request, mediaType));
        }
 public static System.Net.Http.Json.JsonContent Create(object inputValue, System.Type inputType, System.Net.Http.Headers.MediaTypeHeaderValue mediaType = default(System.Net.Http.Headers.MediaTypeHeaderValue), System.Text.Json.JsonSerializerOptions options = default(System.Text.Json.JsonSerializerOptions)) => throw null;
 public JsonContent(object model) : base(JsonSerializer.SerializeToUtf8Bytes(model))
 {
     Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
 }
Beispiel #27
0
 internal static object GetBoundary(System.Net.Http.Headers.MediaTypeHeaderValue mediaTypeHeaderValue, int defaultMultipartBoundaryLengthLimit)
 {
     throw new NotImplementedException();
 }
Beispiel #28
0
        /// <summary>
        /// Returns a specialized instance of the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" /> that can format a response for the given parameters.
        /// </summary>
        /// <param name="type">The type to format.</param>
        /// <param name="request">The request.</param>
        /// <param name="mediaType">The media type.</param>
        /// <returns>
        /// Returns <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" />.
        /// </returns>
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            var    qryParams      = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query);
            string loadAttributes = qryParams["LoadAttributes"] ?? string.Empty;

            // if "simple" or True is specified in the LoadAttributes param, tell the formatter to serialize in Simple mode
            SerializeInSimpleMode = loadAttributes.Equals("simple", StringComparison.OrdinalIgnoreCase) || (loadAttributes.AsBooleanOrNull() ?? false);

            // if either "simple", "expanded", or True is specified in the LoadAttributes param, tell the formatter to load the attributes on the way out
            LoadAttributes = SerializeInSimpleMode || loadAttributes.Equals("expanded", StringComparison.OrdinalIgnoreCase);

            // NOTE: request.Properties["Person"] gets set in Rock.Rest.Filters.SecurityAttribute.OnActionExecuting
            if (LoadAttributes && request.Properties.ContainsKey("Person"))
            {
                this.Person = request.Properties["Person"] as Rock.Model.Person;
            }

            return(base.GetPerRequestFormatterInstance(type, request, mediaType));
        }
Beispiel #29
0
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            string callback;

            if (request.GetQueryNameValuePairs().ToDictionary(pari => pari.Key, pari => pari.Value).TryGetValue("callback", out callback))
            {
                return(new JsonpMediaTypeFormatter(callback));
            }
            return(this);
        }
Beispiel #30
0
 public override void SetDefaultContentHeaders(Type type, System.Net.Http.Headers.HttpContentHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
 {
     base.SetDefaultContentHeaders(type, headers, mediaType);
     headers.ContentType.CharSet = null;
 }