public override bool Execute() { HttpClient client = null; try { var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); var mediaType = new MediaTypeHeaderValue("application/json"); var jsonSerializerSettings = new JsonSerializerSettings(); var requestMessage = new HttpRequestMessage<string>( this.PostContent, mediaType, new MediaTypeFormatter[] { jsonFormatter }); client = new HttpClient(); HttpResponseMessage response = null; System.Threading.Tasks.Task postTask = client.PostAsync(this.Url, requestMessage.Content).ContinueWith(respMessage => { response = respMessage.Result; }); System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { postTask }); response.EnsureSuccessStatusCode(); return true; } catch (Exception ex) { string message = "Unable to post the message."; throw new LoggerException(message,ex); } finally { if (client != null) { client.Dispose(); client = null; } } }
/// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration" />.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator() .ActionSamples.Add( new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] {"*"}), sample); }
/// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration" />.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator() .ActionSamples.Add( new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); }
///<summary> /// Creates a file parameter from an array of bytes. ///</summary> ///<param name="name">The parameter name to use in the request.</param> ///<param name="input">The input stream for the file's contents.</param> ///<param name="filename">The filename to use in the request.</param> ///<param name="contentType">The content type to use in the request.</param> ///<returns>The <see cref="FileParameter"/></returns> public static FileParameter Create(string name, Stream input, string filename, MediaTypeHeaderValue contentType) { var temp = new MemoryStream(); input.CopyTo(temp); var data = temp.ToArray(); return Create(name, data, filename, contentType); }
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { base.SetDefaultContentHeaders(type, headers, mediaType); headers.ContentType = new MediaTypeHeaderValue(ApplicationJsonMediaType); this.SerializerSettings.Formatting = Formatting.None; this.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { base.SetDefaultContentHeaders(type, headers, mediaType); // Remove charset parameter. It must not be sent according to Json Api (http://jsonapi.org/format/#content-negotiation-servers) headers.ContentType.CharSet = null; }
protected virtual string MakeCachekey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false) { var controller = context.ControllerContext.ControllerDescriptor.ControllerName; var action = context.ActionDescriptor.ActionName; var key = context.Request.GetConfiguration().CacheOutputConfiguration().MakeBaseCachekey(controller, action); var parametersCollections = context.ActionArguments.Where(x => x.Value != null).Select(x => x.Key + "=" + x.Value); var parameters = "-"+string.Join("&", parametersCollections); if (excludeQueryString) { parameters = string.Empty; } else { var callbackValue = GetJsonpCallback(context.Request); if (!string.IsNullOrWhiteSpace(callbackValue)) { var callback = "callback=" + callbackValue; if (parameters.Contains("&" + callback)) parameters = parameters.Replace("&" + callback, string.Empty); if (parameters.Contains(callback + "&")) parameters = parameters.Replace(callback + "&", string.Empty); if (parameters.Contains("-" + callback)) parameters = parameters.Replace("-" + callback, string.Empty); if (parameters.EndsWith("&")) parameters = parameters.TrimEnd('&'); } } if (parameters == "-") parameters = string.Empty; var cachekey = string.Format("{0}{1}:{2}", key, parameters, mediaType.MediaType); return cachekey; }
public FileRepresentationModel(string filename, string fileExtension, byte[] contentAsByteArray, MediaTypeHeaderValue mediaTypeHeaderValue) { Filename = filename; FileExtension = fileExtension; ContentAsByteArray = contentAsByteArray; MediaTypeHeaderValue = mediaTypeHeaderValue; }
public static MapRepresentation Create(IOidStrategy oidStrategy, HttpRequestMessage req, ContextFacade contextFacade, IList<ContextFacade> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) { var memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, req, c, flags))).ToList(); IObjectFacade target = contexts.First().Target; MapRepresentation mapRepresentation; if (format == Format.Full) { var tempProperties = new List<OptionalProperty>(); if (!string.IsNullOrEmpty(contextFacade?.Reason)) { tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason)); } var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName(oidStrategy)); tempProperties.Add(dt); var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues.ToArray())); tempProperties.Add(members); mapRepresentation = Create(tempProperties.ToArray()); } else { mapRepresentation = Create(memberValues.ToArray()); } mapRepresentation.SetContentType(mt); return mapRepresentation; }
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType) { if (_viewLocator == null || _viewParser == null) { var config = request.GetConfiguration(); if (config != null) { IViewLocator viewLocator = null; IViewParser viewParser = null; var resolver = config.DependencyResolver; if (_viewLocator == null) viewLocator = (IViewLocator) resolver.GetService(typeof (IViewLocator)); if (_viewParser == null) viewParser = (IViewParser) resolver.GetService(typeof (IViewParser)); return new HtmlMediaTypeViewFormatter(_siteRootPath, viewLocator, viewParser); } } 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, HttpRequestMessage request, MediaTypeHeaderValue mediaType) { var parameters = request.RequestUri.ParseQueryString(); var prettify = false; if (parameters[PrettifyParameterName] != null) { prettify = new[] { "yes", "1", "true" }.Contains(parameters[PrettifyParameterName], StringComparer.OrdinalIgnoreCase); } var fieldNamingStratgey = _fieldNamingStratgey; if (parameters[FieldNamingStrategyParameterName] != null) { switch (parameters[FieldNamingStrategyParameterName]) { case "none": fieldNamingStratgey = new DefaultFieldNamingStrategy(); break; case "dash": fieldNamingStratgey = new DasherizedFieldNamingStrategy(); break; case "snake": fieldNamingStratgey = new SnakeCaseNamingStrategy(); break; } } return new JsonApiMediaTypeFormatter(ContractResolver, fieldNamingStratgey, prettify); }
public void Negotiate_ForRequestReturnsFirstMatchingFormatter() { MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/myMediaType"); MediaTypeFormatter formatter1 = new MockMediaTypeFormatter() { CanWriteTypeCallback = (Type t) => false }; MediaTypeFormatter formatter2 = new MockMediaTypeFormatter() { CanWriteTypeCallback = (Type t) => true }; formatter2.SupportedMediaTypes.Add(mediaType); MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection( new MediaTypeFormatter[] { formatter1, formatter2 }); _request.Content = new StringContent("test", Encoding.Default, mediaType.MediaType); var result = _negotiator.Negotiate(typeof(string), _request, collection); Assert.Same(formatter2, result.Formatter); Assert.MediaType.AreEqual(mediaType, result.MediaType, "Expected the formatter's media type to be returned."); }
/// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; MediaType = mediaType; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; }
/// <summary> /// Constructor which initializes this serializer /// </summary> public JsonSerializer() { ContentType = new MediaTypeHeaderValue("application/json") { CharSet = _encoding.WebName, }; }
public OpenSearchDescription(MediaTypeHeaderValue contentType, Stream stream) : this(XDocument.Load(stream)) { //if (contentType.MediaType != "application/opensearchdescription+xml") //{ // throw new NotSupportedException("Do not understand " + contentType.MediaType + " as a search description language"); //} }
public StringResponseWriter(string text, MediaTypeHeaderValue contentType) { VerifyArgument.IsNotNull("mediaType", contentType); _text = text; _contentType = contentType; _enforceSizeCap = true; }
public ParsedMediaTypeHeaderValue(MediaTypeHeaderValue mediaType) { this.mediaType = mediaType; string[] splitMediaType = mediaType.MediaType.Split(MediaTypeSubTypeDelimiter); this.type = splitMediaType[0]; this.subType = splitMediaType[1]; }
public TypedJsonMediaTypeFormatter(Type resourceType, MediaTypeHeaderValue mediaType) { this.resourceType = resourceType; this.SupportedMediaTypes.Clear(); this.SupportedMediaTypes.Add(mediaType); }
public override void OnActionExecuting(HttpActionContext ac) { if (ac != null) { if (_isCacheable(ac)) { _cachekey = string.Join(":", new string[] { ac.Request.RequestUri.AbsolutePath, ac.Request.Headers.Accept.FirstOrDefault().ToString() }); if (WebApiCache.Contains(_cachekey)) { var val = (string)WebApiCache.Get(_cachekey); if (val != null) { var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct"); if (contenttype == null) contenttype = new MediaTypeHeaderValue(_cachekey.Split(':')[1]); ac.Response = ac.Request.CreateResponse(); ac.Response.Content = new StringContent(val); ac.Response.Content.Headers.ContentType = contenttype; ac.Response.Headers.CacheControl = setClientCache(); return; } } } } else { throw new ArgumentNullException("actionContext"); } }
public void Constructor(string queryStringParameterName, string queryStringParameterValue, MediaTypeHeaderValue mediaType) { QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType); Assert.Equal(queryStringParameterName, mapping.QueryStringParameterName); Assert.Equal(queryStringParameterValue, mapping.QueryStringParameterValue); Assert.MediaType.AreEqual(mediaType, mapping.MediaType, "MediaType failed to set."); }
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request,MediaTypeHeaderValue mediaType) { //所需的对象属性 var includingFields = request.GetRouteData().Values["fields"]; if (includingFields != null && !string.IsNullOrEmpty(includingFields.ToString())) { FieldsJsonMediaTypeFormatter frmtr = new FieldsJsonMediaTypeFormatter(); frmtr.CurrentRequest = request; var resolve = new Share.IncludableSerializerContractResolver(this.SerializerSettings.ContractResolver as Share.IgnorableSerializerContractResolver); //type.IsAssignableFrom(typeof(IEnumerable<Model.dr_pre_visit>)) if (type.GetInterface("IEnumerable") != null) { resolve.Include(type.GenericTypeArguments[0], includingFields.ToString(), ','); } else { resolve.Include(type, includingFields.ToString(), ","); } frmtr.SerializerSettings = new JsonSerializerSettings { ContractResolver = resolve, }; return frmtr; } else { return this; } }
public override void OnActionExecuting(HttpActionContext context) { if (context == null) { throw new ArgumentNullException("actionContext"); } else if (this.IsCacheable(context)) { cachekey = string.Join(":", context.Request.RequestUri.AbsolutePath, context.Request.Headers.Accept.FirstOrDefault().ToString()); if (WebApiOutputCacheAttribute.webApiCache.Contains(this.cachekey)) { var val = WebApiOutputCacheAttribute.webApiCache.Get(this.cachekey) as string; if (val != null) { var contenttype = WebApiOutputCacheAttribute.webApiCache.Get(cachekey + ":response-ct") as MediaTypeHeaderValue; if (contenttype == null) { contenttype = new MediaTypeHeaderValue(this.cachekey.Split(':')[1]); } context.Response = context.Request.CreateResponse(); context.Response.Content = new StringContent(val); context.Response.Content.Headers.ContentType = contenttype; context.Response.Headers.CacheControl = this.SetClientCache(); return; } } } }
public void Equals_Returns_True_If_MediaTypes_Differ_Only_By_Case() { MediaTypeHeaderValueEqualityComparer comparer = MediaTypeHeaderValueEqualityComparer.EqualityComparer; MediaTypeHeaderValue mediaType1 = new MediaTypeHeaderValue("text/xml"); MediaTypeHeaderValue mediaType2 = new MediaTypeHeaderValue("TEXT/xml"); Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'."); mediaType1 = new MediaTypeHeaderValue("text/*"); mediaType2 = new MediaTypeHeaderValue("TEXT/*"); Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'."); mediaType1 = new MediaTypeHeaderValue("*/*"); mediaType2 = new MediaTypeHeaderValue("*/*"); Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'."); mediaType1 = new MediaTypeHeaderValue("text/*"); mediaType1.CharSet = "someCharset"; mediaType2 = new MediaTypeHeaderValue("TEXT/*"); mediaType2.CharSet = "SOMECHARSET"; Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'."); mediaType1 = new MediaTypeHeaderValue("application/*"); mediaType1.CharSet = ""; mediaType2 = new MediaTypeHeaderValue("application/*"); mediaType2.CharSet = null; Assert.IsTrue(comparer.Equals(mediaType1, mediaType2), "Equals should have returned 'true'."); }
public static MapRepresentation Create(HttpRequestMessage req, IList<ContextSurface> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) { OptionalProperty[] memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToArray(); INakedObjectSurface target = contexts.First().Target; MapRepresentation mapRepresentation; if (format == Format.Full) { var tempProperties = new List<OptionalProperty>(); if (flags.SimpleDomainModel) { var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName()); tempProperties.Add(dt); } if (flags.FormalDomainModel) { var links = new OptionalProperty(JsonPropertyNames.Links, new[] { Create(new OptionalProperty(JsonPropertyNames.Rel, RelValues.DescribedBy), new OptionalProperty(JsonPropertyNames.Href, new UriMtHelper(req, target.Specification).GetDomainTypeUri())) }); tempProperties.Add(links); } var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues)); tempProperties.Add(members); mapRepresentation = Create(tempProperties.ToArray()); } else { mapRepresentation = Create(memberValues); } mapRepresentation.SetContentType(mt); return mapRepresentation; }
public static MapRepresentation Create(HttpRequestMessage req, ContextSurface context, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) { var objectContextSurface = context as ObjectContextSurface; var actionResultContextSurface = context as ActionResultContextSurface; MapRepresentation mapRepresentation; if (objectContextSurface != null) { List<OptionalProperty> optionalProperties = objectContextSurface.VisibleProperties.Where(p => p.Reason != null || p.ProposedValue != null).Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToList(); if (!string.IsNullOrEmpty(objectContextSurface.Reason)) { optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, objectContextSurface.Reason)); } mapRepresentation = Create(optionalProperties.ToArray()); } else if (actionResultContextSurface != null) { List<OptionalProperty> optionalProperties = actionResultContextSurface.ActionContext.VisibleParameters.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToList(); if (!string.IsNullOrEmpty(actionResultContextSurface.Reason)) { optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, actionResultContextSurface.Reason)); } mapRepresentation = Create(optionalProperties.ToArray()); } else { mapRepresentation = GetMap(req, context, flags); } mapRepresentation.SetContentType(mt); return mapRepresentation; }
public RouteDataMapping(string routeDataValueName, string routeDataValueValue, MediaTypeHeaderValue mediaType) : base(mediaType) { _routeDataValueName = routeDataValueName; _routeDataValueValue = routeDataValueValue; }
public void GetMediaType_HandlesUnknownMediaTypes(string extension) { MediaTypeMap map = new MediaTypeMap(); MediaTypeHeaderValue expectedMediaType = new MediaTypeHeaderValue("application/octet-stream"); Assert.Equal(expectedMediaType, map.GetMediaType(extension)); }
public void Ctor_MediaTypeValidFormat_SuccessfullyCreated() { MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("text/plain"); Assert.Equal("text/plain", mediaType.MediaType); Assert.Equal(0, mediaType.Parameters.Count); Assert.Null(mediaType.CharSet); }
/// <summary> /// Validate HttpResponse message, throws an Api Exception with context /// </summary> /// <param name="response"></param> /// <param name="request"></param> /// <param name="apiContext"></param> /// <exception cref="ApiException"></exception> public static void EnsureSuccess(HttpResponseMessage response, HttpRequestMessage request=null, IApiContext apiContext=null) { if (response.IsSuccessStatusCode) return; if (response.StatusCode == HttpStatusCode.NotModified) return; var content = response.Content.ReadAsStringAsync().Result; ApiException exception ; var htmlMediaType = new MediaTypeHeaderValue("text/html"); if (response.Content.Headers.ContentType != null && response.Content.Headers.ContentType.MediaType == htmlMediaType.MediaType) { var message = String.Format("Status Code {0}, Uri - {1}", response.StatusCode, response.RequestMessage.RequestUri.AbsoluteUri); exception = new ApiException(message, new Exception(content)); } else if (!String.IsNullOrEmpty(content)) exception = JsonConvert.DeserializeObject<ApiException>(content); else if (HttpStatusCode.NotFound == response.StatusCode && string.IsNullOrEmpty(content) && request != null) exception = new ApiException("Uri "+request.RequestUri.AbsoluteUri + " does not exist"); else exception = new ApiException("Unknow Exception"); exception.HttpStatusCode = response.StatusCode; exception.CorrelationId = HttpHelper.GetHeaderValue(Headers.X_VOL_CORRELATION, response.Headers); exception.ApiContext = apiContext; if (!MozuConfig.ThrowExceptionOn404 && string.Equals(exception.ErrorCode, "ITEM_NOT_FOUND", StringComparison.OrdinalIgnoreCase) && response.RequestMessage.Method.Method == "GET") return; throw exception; }
/// <summary> /// Creates a new <see cref="HelpPageSampleKey" /> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) throw new ArgumentNullException("type"); this.ParameterType = type; }