/// <summary> /// Initializes a new instance of the <see cref="JsonpMediaTypeFormatter"/> class. /// </summary> /// <param name="jsonMediaTypeFormatter">The <see cref="JsonMediaTypeFormatter"/> to use internally for JSON serialization.</param> /// <param name="callbackQueryParameter">The query parameter containing the callback.</param> public JsonpMediaTypeFormatter(MediaTypeFormatter jsonMediaTypeFormatter, string callbackQueryParameter = "callback") { if (jsonMediaTypeFormatter == null) { throw new ArgumentNullException("jsonMediaTypeFormatter"); } if (callbackQueryParameter == null) { throw new ArgumentNullException("callbackQueryParameter"); } _jsonMediaTypeFormatter = jsonMediaTypeFormatter; _callbackQueryParameter = callbackQueryParameter; SupportedMediaTypes.Add(_textJavaScript); SupportedMediaTypes.Add(_applicationJavaScript); SupportedMediaTypes.Add(_applicationJsonp); foreach (var encoding in _jsonMediaTypeFormatter.SupportedEncodings) { SupportedEncodings.Add(encoding); } MediaTypeMappings.Add(new QueryStringMapping("format", "jsonp", _textJavaScript)); MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", _textJavaScript)); }
private void Bind(string methodName) { //创建FormatterParameterBinding对象 MethodInfo method = typeof(ContactsController).GetMethod(methodName); HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(this.ControllerContext.ControllerDescriptor, method); HttpParameterDescriptor parameterDescriptor = actionDescriptor.GetParameters().First(); MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }; FormatterParameterBinding parameterBinding = new FormatterParameterBinding(parameterDescriptor, formatters, null); //创建HttpActionBinding并执行 HttpActionBinding actionBinding = new HttpActionBinding(actionDescriptor,new FormatterParameterBinding[] { parameterBinding }); HttpActionContext actionContext =new HttpActionContext(this.ControllerContext, actionDescriptor); try { actionBinding.ExecuteBindingAsync(actionContext, CancellationToken.None).Wait(); //获取绑定参数对象并打印相关数据 Contact contact = (Contact)actionContext.ActionArguments["contact"]; Console.WriteLine("{0,-12}: {1}", "Name", contact.Name); Console.WriteLine("{0,-12}: {1}", "Phone No.", contact.PhoneNo); Console.WriteLine("{0,-12}: {1}", "EmailAddress", contact.EmailAddress); Console.WriteLine("{0,-12}: {1}", "Address", contact.Address); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public PseudoMediaTypeFormatter(MediaTypeFormatter referFormatter = null) { SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true)); _ReferFormatter = referFormatter ?? new JsonMediaTypeFormatter(); }
public PropertiesForm(HttpClient client, Uri propertiesUri, MediaTypeFormatter formatter) { InitializeComponent(); Switch = client; PropertiesUri = propertiesUri; Formatter = formatter; }
private static void AddSupportedEncodings(MediaTypeFormatter formatter) { formatter.SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); formatter.SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true)); }
private static void CreateMediaTypes(MediaTypeFormatter mediaTypeFormatter, IEnumerable<string> mediaTypes) { //Vendor specific media types http://www.iana.org/cgi-bin/mediatypes.pl foreach (var mediaType in mediaTypes) { mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(mediaType)); } }
private static void CreateXmlMediaTypes(MediaTypeFormatter xmlFormatter) { var mediaTypes = new List<string> { "application/vnd.bekk.kh.v1+xml", "application/vnd.bekk.kh.v2+xml" }; CreateMediaTypes(xmlFormatter, mediaTypes); }
protected HttpRequestMessage CriarRequest(string url, HttpMethod method, object content = null, string mediaType = "application/json", MediaTypeFormatter formatter = null) { var request = new HttpRequestMessage { RequestUri = new Uri(urlBase + url), Method = method }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType)); if (content!=null) request.Content = new ObjectContent(content.GetType(), content, formatter ?? new JsonMediaTypeFormatter()); return request; }
public void ReadAsAsyncOfT_WhenTypeIsReferenceTypeAndNoMediaType_ReturnsNull() { var content = new StringContent("{}"); content.Headers.ContentType = null; var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }; Assert.Equal(null, content.ReadAsAsync<List<string>>(formatters).Result); }
public WebApiConfigModule(IDependencyResolver dependencyResolver, HttpConfiguration apiConfig, MediaTypeFormatter jsonFormatter) { _dependencyResolver = dependencyResolver; _apiConfig = apiConfig; _jsonFormatter = jsonFormatter; }
public static MediaTypeFormatter CreateTracer(MediaTypeFormatter formatter, ITraceWriter traceWriter, HttpRequestMessage request) { // If we have been asked to wrap a tracer around a formatter, it could be // already wrapped, and there is nothing to do. But if we see it is a tracer // that is not associated with a request, we wrap it into a new tracer that // does have a request. The only formatter tracers without requests are the // ones in the default MediaTypeFormatterCollection in the HttpConfiguration. IFormatterTracer formatterTracer = formatter as IFormatterTracer; if (formatterTracer != null) { if (formatterTracer.Request == request) { return formatter; } formatter = formatterTracer.InnerFormatter; } MediaTypeFormatter tracer = null; // We special-case Xml, Json and FormUrlEncoded formatters because we expect to be able // to find them with IsAssignableFrom in the MediaTypeFormatterCollection. if (formatter is XmlMediaTypeFormatter) { tracer = new XmlMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is JsonMediaTypeFormatter) { tracer = new JsonMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is FormUrlEncodedMediaTypeFormatter) { tracer = new FormUrlEncodedMediaTypeFormatterTracer(formatter, traceWriter, request); } else if (formatter is BufferedMediaTypeFormatter) { tracer = new BufferedMediaTypeFormatterTracer(formatter, traceWriter, request); } else { tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request); } // Copy SupportedMediaTypes and MediaTypeMappings because they are publically visible tracer.SupportedMediaTypes.Clear(); foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { tracer.SupportedMediaTypes.Add(mediaType); } tracer.MediaTypeMappings.Clear(); foreach (MediaTypeMapping mapping in formatter.MediaTypeMappings) { tracer.MediaTypeMappings.Add(mapping); } return tracer; }
public void ReadAsAsyncOfT_WhenNoMatchingFormatterFoundForContentWithNoMediaType_Throws() { var content = new StringContent("{}"); content.Headers.ContentType = null; var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }; Assert.Throws<InvalidOperationException>(() => content.ReadAsAsync<List<string>>(formatters), "No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type ''undefined''."); }
public ODataFormatterParameterBinding(HttpParameterDescriptor descriptor, MediaTypeFormatter formatter) : base(descriptor) { if (formatter == null) { throw Error.ArgumentNull("formatter"); } _formatter = formatter; }
public void Post() { IEnumerable<MediaTypeFormatter> formatters = new MediaTypeFormatter[] { new FormUrlEncodedMediaTypeFormatter() }; FormDataCollection formData = this.Request.Content.ReadAsAsync<FormDataCollection>(formatters).Result; foreach (var item in formData) { Console.WriteLine("{0,-12}: {1}", item.Key, item.Value); } }
private PocoRuntime() { Grammar = new ODataGrammar(); UsePluralUrls = true; UriBuilder = new EntityUriBuilder(); RequestSetup = (request) => {}; DisposeHandler = true; CustomFormatters = new MediaTypeFormatter[0]; }
private async Task<List<Persona>> ObtenerPersonas() { List<Persona> personas = null; // Creación de instancia de HttpClient para acceder a servicio Web API. using (HttpClient cliente = new HttpClient()) { // URL donde se encuentra alojado el servicio Web API. cliente.BaseAddress = new Uri("http://localhost:60461"); // Adicionar encabezado con el tipo de contenido (application/bson). // Con esta instrucción, el servicio Web API determina la serialización a usar. cliente.DefaultRequestHeaders.Accept.Clear(); cliente.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson")); // Enviar petición al servicio. var resultado = await cliente.GetAsync("api/personas"); resultado.EnsureSuccessStatusCode(); // Deserializar el resultado. MediaTypeFormatter[] formatos = new MediaTypeFormatter[] { new BsonMediaTypeFormatter() }; personas = await resultado.Content.ReadAsAsync<List<Persona>>(formatos); } return personas; }
/// <summary> /// Creates a new entry point using an OAuth token. /// </summary> /// <param name="uri">The base URI of the REST interface. Missing trailing slash will be appended automatically.</param> /// <param name="token">The OAuth token to present as a "Bearer" to the REST interface.</param> /// <param name="serializer">Controls the serialization of entities sent to and received from the server. Defaults to a JSON serializer if unset.</param> public EntryEndpoint(Uri uri, string token, MediaTypeFormatter serializer = null) : base( uri: uri.EnsureTrailingSlash(), httpClient: BuildHttpClient(uri), serializer: serializer ?? BuildSerializer()) { HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); }
public void ReadAsAsyncOfT_WhenTypeIsReferenceTypeAndNoMediaType_Throws() { var content = new StringContent("{}"); content.Headers.ContentType = null; var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }; Assert.Throws<UnsupportedMediaTypeException>(() => content.ReadAsAsync<List<string>>(formatters), "No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'application/octet-stream'."); }
private static void CreateJsonMediaTypes(MediaTypeFormatter jsonFormatter) { var mediaTypes = new List<string> { "application/vnd.bekk.kh.v1+json", "application/vnd.bekk.kh.v2+json" }; CreateMediaTypes(jsonFormatter, mediaTypes); }
public void Post() { IEnumerable<MediaTypeFormatter> formatters = new MediaTypeFormatter[] { new XmlMediaTypeFormatter() }; Contact contact = this.Request.Content.ReadAsAsync<Contact>(formatters).Result; Console.WriteLine("{0,-12}: {1}", "Name", contact.Name); Console.WriteLine("{0,-12}: {1}", "Phone No.", contact.PhoneNo); Console.WriteLine("{0,-12}: {1}", "EmailAddress", contact.EmailAddress); Console.WriteLine("{0,-12}: {1}", "Address", contact.Address); }
/// <summary> /// Returns a <see cref="Task{T}"/> that will yield a <see cref="NameValueCollection"/> instance containing the form data /// parsed as HTML form URL-encoded from the <paramref name="content"/> instance. /// </summary> /// <param name="content">The content.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A <see cref="Task{T}"/> which will provide the result. If the data can not be read /// as HTML form URL-encoded data then the result is null.</returns> public static Task<NameValueCollection> ReadAsFormDataAsync(this HttpContent content, CancellationToken cancellationToken) { if (content == null) { throw Error.ArgumentNull("content"); } MediaTypeFormatter[] formatters = new MediaTypeFormatter[1] { new FormUrlEncodedMediaTypeFormatter() }; return ReadAsAsyncCore(content, formatters, cancellationToken); }
/// <summary> /// Create the content negotiation result object. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The preferred media type. Can be <c>null</c>.</param> public ContentNegotiationResult(MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw Error.ArgumentNull("formatter"); } _formatter = formatter; MediaType = mediaType; }
/// <summary> /// Create the content negotiation result object. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The preferred media type. Can be <c>null</c>.</param> public ContentNegotiationResult(MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } _formatter = formatter; MediaType = mediaType; }
public FiveLevelsOfMediaTypeFormatter(MediaTypeFormatter internalFormatter) { _internalFormatter = internalFormatter; _internalFormatter.SupportedEncodings.Each(x=> SupportedEncodings.Add(x)); _internalFormatter.SupportedMediaTypes.Each(x => SupportedMediaTypes.Add(x)); _internalFormatter.MediaTypeMappings.Each(x => MediaTypeMappings.Add(x)); _supportedNonCanonicalMediaTypePatterns.Add( DefaultNonCanonicalMediaTypePattern); }
public override HttpResponseMessage GetAsMessage(MediaTypeFormatter formatter, Tuple<int, int, int> cacheSettings) { var content = new StreamContent(AsStream); var msg = new HttpResponseMessage {Content = content}; msg.Content.Headers.ContentDisposition = ContentDisposition; msg.Content.Headers.ContentType = GetContentType(); SetCaching(msg, cacheSettings); return msg; }
public void ReadAsAsyncOfT_WhenNoMatchingFormatterFound_Throws() { var content = new StringContent("{}"); content.Headers.ContentType = _mediaType; content.Headers.ContentType.CharSet = "utf-16"; var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }; Assert.Throws<InvalidOperationException>(() => content.ReadAsAsync<List<string>>(formatters), "No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'foo/bar'."); }
/// <summary> /// Creates a new REST endpoint with an absolute URI. /// </summary> /// <param name="uri">The HTTP URI of the remote element.</param> /// <param name="httpClient">The HTTP client used to communicate with the remote element.</param> /// <param name="serializer">Controls the serialization of entities sent to and received from the server.</param> protected EndpointBase(Uri uri, HttpClient httpClient, MediaTypeFormatter serializer) { if (uri == null) throw new ArgumentNullException(nameof(uri)); if (httpClient == null) throw new ArgumentNullException(nameof(httpClient)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); Uri = uri; HttpClient = httpClient; Serializer = serializer; }
/// <summary> /// Initializes a new instance of the <see cref="JsonContractResolver" /> class. /// </summary> /// <param name="formatter">The formatter to use for resolving required members.</param> public JsonContractResolver(MediaTypeFormatter formatter) { if (formatter == null) { throw Error.ArgumentNull("formatter"); } _formatter = formatter; // Need this setting to have [Serializable] types serialized correctly IgnoreSerializableAttribute = false; }
public WebApiHttpServer(string serverUrl, MediaTypeFormatter formatter) { var config = new HttpSelfHostConfiguration(serverUrl); config.Formatters.Add(formatter); config.Routes.MapHttpRoute( "API Default", "{controller}/{action}", new { id = RouteParameter.Optional }); Server = new HttpSelfHostServer(config); Server.OpenAsync().Wait(); }
/// <summary> /// Initializes a new instance of the <see cref="MediaTypeFormatterMatch"/> class. /// </summary> /// <param name="formatter">The matching formatter.</param> /// <param name="mediaType"> /// The media type. Can be <c>null</c> in which case the media type <c>application/octet-stream</c> is used. /// </param> /// <param name="quality"> /// The quality of the match. Can be <c>null</c> in which case it is considered a full match with a value of /// 1.0. /// </param> /// <param name="ranking">The kind of match.</param> public MediaTypeFormatterMatch( MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, double? quality, MediaTypeFormatterMatchRanking ranking) { Formatter = formatter; MediaType = mediaType != null ? mediaType : MediaTypeConstants.ApplicationOctetStreamMediaType; Quality = quality ?? FormattingUtilities.Match; Ranking = ranking; }
public void AddUriPathExtensionMapping_MediaType_ThrowsWithNullThis() { MediaTypeFormatter formatter = null; Assert.ThrowsArgumentNull(() => formatter.AddUriPathExtensionMapping("xml", "application/xml"), "formatter"); }