// GET api/<num> public HttpResponseMessage Get(int? id, string extension = "json") { var results = GetComputedResults(id); MediaTypeFormatter fmtr = null; switch (extension) { case "plain-text": //TODO: write formatter fmtr = new PlainTextMediaFormatter(); break; case "xml": fmtr = new XmlMediaTypeFormatter() { UseXmlSerializer = true }; break; case "json": fmtr = new JsonMediaTypeFormatter(); JsonMediaTypeFormatter f = fmtr as JsonMediaTypeFormatter; break; } if (fmtr == null) { return new HttpResponseMessage(HttpStatusCode.NotFound); } return new HttpResponseMessage() { Content = new ObjectContent<FibonacciResultSet>( results, fmtr ) }; }
static async void RunClient() { try { Console.WriteLine("Translating English phrase {0} (might take some seconds)...", "Hello World"); // Create client and insert a message handler that obtains an Azure Marketplace Access Token in the message path HttpClient client = new HttpClient(new AccessTokenMessageHandler(new HttpClientHandler())); // Create BING translate options data which we send along with the HTTP request as part of the HTTP request body. // TranslateOptions is a type provided by BING translation service. TranslateOptions options = new TranslateOptions("", "defaultUser"); // Send asynchronous request to BING translation API MediaTypeFormatter xmlFormatter = new XmlMediaTypeFormatter { UseXmlSerializer = true }; HttpResponseMessage response = await client.PostAsync<TranslateOptions>(_address, options, xmlFormatter); // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as GetTranslationsResponse which is a type defined by BING translation service GetTranslationsResponse translation = await response.Content.ReadAsAsync<GetTranslationsResponse>(new[] { xmlFormatter }); Console.WriteLine(); Console.WriteLine("...{0}", translation.Translations[0].TranslatedText); } catch (Exception e) { Console.WriteLine("Request caused exception: {0}", e.Message); } }
private static void AddDataControllerFormatters(List<MediaTypeFormatter> formatters, DataControllerDescription description) { var cachedSerializers = _serializerCache.GetOrAdd(description.ControllerType, controllerType => { // for the specified controller type, set the serializers for the built // in framework types List<SerializerInfo> serializers = new List<SerializerInfo>(); Type[] exposedTypes = description.EntityTypes.ToArray(); serializers.Add(GetSerializerInfo(typeof(ChangeSetEntry[]), exposedTypes)); return serializers; }); JsonMediaTypeFormatter formatterJson = new JsonMediaTypeFormatter(); formatterJson.SerializerSettings = new JsonSerializerSettings() { PreserveReferencesHandling = PreserveReferencesHandling.Objects, TypeNameHandling = TypeNameHandling.All }; XmlMediaTypeFormatter formatterXml = new XmlMediaTypeFormatter(); // apply the serializers to configuration foreach (var serializerInfo in cachedSerializers) { formatterXml.SetSerializer(serializerInfo.ObjectType, serializerInfo.XmlSerializer); } formatters.Add(formatterJson); formatters.Add(formatterXml); }
public static void ConfigureWebApi(HttpConfiguration httpConfiguration, EntityApp app, LogLevel logLevel = LogLevel.Basic, WebHandlerOptions webHandlerOptions = WebHandlerOptions.DefaultDebug) { // Logging message handler var webHandlerStt = new WebCallContextHandlerSettings(logLevel, webHandlerOptions); var webContextHandler = new WebCallContextHandler(app, webHandlerStt); httpConfiguration.MessageHandlers.Add(webContextHandler); // Exception handling filter - to handle/save exceptions httpConfiguration.Filters.Add(new ExceptionHandlingFilter()); // Formatters - add formatters with spies, to catch/log deserialization failures httpConfiguration.Formatters.Clear(); httpConfiguration.Formatters.Add(new StreamMediaTypeFormatter("image/jpeg", "image/webp")); //webp is for Chrome var xmlFmter = new XmlMediaTypeFormatter(); httpConfiguration.Formatters.Add(xmlFmter); var jsonFmter = new JsonMediaTypeFormatter(); // add converter that will serialize all enums as strings, not integers jsonFmter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); var resolver = jsonFmter.SerializerSettings.ContractResolver = new JsonContractResolver(jsonFmter); httpConfiguration.Formatters.Add(jsonFmter); //Api configuration if (app.ApiConfiguration.ControllerInfos.Count > 0) ConfigureSlimApi(httpConfiguration, app); }
public void XmlFormatter_SetByCtor() { XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[] { formatter }); Assert.Same(formatter, collection.XmlFormatter); }
/// <summary> /// Initializes a new instance of the <see cref="XmlMediaTypeFormatter"/> class. /// </summary> /// <param name="formatter">The <see cref="XmlMediaTypeFormatter"/> instance to copy settings from.</param> protected XmlMediaTypeFormatter(XmlMediaTypeFormatter formatter) : base(formatter) { UseXmlSerializer = formatter.UseXmlSerializer; WriterSettings = formatter.WriterSettings; #if !NETFX_CORE // MaxDepth is not supported in portable libraries MaxDepth = formatter.MaxDepth; #endif }
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { var xmlFormater = new XmlMediaTypeFormatter { UseXmlSerializer = true }; controllerSettings.Formatters.Clear(); controllerSettings.Formatters.Add(xmlFormater); }
public XmlMediaTypeFormatterTracer(XmlMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request) { _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request); // copy values we cannot override _innerTracer.CopyNonOverriableMembersFromInner(this); UseXmlSerializer = innerFormatter.UseXmlSerializer; Indent = innerFormatter.Indent; MaxDepth = innerFormatter.MaxDepth; }
/// <summary> /// Checks if request accepts xml as response type /// </summary> /// <param name="xmlFormatter"></param> /// <param name="headers"></param> /// <returns></returns> private bool AcceptsXml(XmlMediaTypeFormatter xmlFormatter, IDictionary<string, string[]> headers) { if (xmlFormatter == null) return false; if (XmlMimeTypes.Any(xml => HasAcceptHeader(headers, xml))) return true; return false; }
public void Insert_SetsXmlFormatter() { MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(); int count = collection.Count; XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); collection.Insert(0, formatter); Assert.Same(formatter, collection.XmlFormatter); Assert.Equal(count + 1, collection.Count); }
public void Indent_Uses_Inners() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); XmlMediaTypeFormatter innerFormatter = new XmlMediaTypeFormatter(); innerFormatter.Indent = !innerFormatter.Indent; XmlMediaTypeFormatterTracer tracer = new XmlMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request); // Act & Assert Assert.Equal(innerFormatter.Indent, tracer.Indent); }
public void UseXmlSerializer_Uses_Inners() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); XmlMediaTypeFormatter innerFormatter = new XmlMediaTypeFormatter(); innerFormatter.UseXmlSerializer = !innerFormatter.UseXmlSerializer; XmlMediaTypeFormatterTracer tracer = new XmlMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request); // Act & Assert Assert.Equal(innerFormatter.UseXmlSerializer, tracer.UseXmlSerializer); }
public void MaxDepth_Uses_Inners() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); XmlMediaTypeFormatter innerFormatter = new XmlMediaTypeFormatter(); innerFormatter.MaxDepth = innerFormatter.MaxDepth + 1; XmlMediaTypeFormatterTracer tracer = new XmlMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request); // Act & Assert Assert.Equal(innerFormatter.MaxDepth, tracer.MaxDepth); }
public void Inner_Property_On_XmlMediaTypeFormatterTracer_Returns_XmlMediaTypeFormatter() { // Arrange XmlMediaTypeFormatter expectedInner = new XmlMediaTypeFormatter(); XmlMediaTypeFormatterTracer productUnderTest = new XmlMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage()); // Act XmlMediaTypeFormatter actualInner = productUnderTest.Inner; // Assert Assert.Same(expectedInner, actualInner); }
public void Decorator_GetInner_On_XmlMediaTypeFormatterTracer_Returns_XmlMediaTypeFormatter() { // Arrange XmlMediaTypeFormatter expectedInner = new XmlMediaTypeFormatter(); XmlMediaTypeFormatterTracer productUnderTest = new XmlMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage()); // Act XmlMediaTypeFormatter actualInner = Decorator.GetInner(productUnderTest as XmlMediaTypeFormatter); // Assert Assert.Same(expectedInner, actualInner); }
protected virtual System.Net.Http.HttpResponseMessage GetResponseMessage <T>(string requestUri, T postData) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ContentType.AsContentTypeString())); if (AuthenticationMethod == AuthenticationType.OAuth && !string.IsNullOrEmpty(_bearerToken)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _bearerToken); } MediaTypeFormatter mediaFormatter; if (ContentType == RequestContentType.ApplicationXml) { mediaFormatter = new System.Net.Http.Formatting.XmlMediaTypeFormatter(); } else { mediaFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter(); } HttpResponseMessage responseMsg = null; if (OperationMethod == HttpMethod.Get) { responseMsg = client.GetAsync(requestUri).Result; } else if (OperationMethod == HttpMethod.Delete && postData == null) { responseMsg = client.DeleteAsync(requestUri).Result; } else if (OperationMethod == HttpMethod.Head) { var rqstMsg = new HttpRequestMessage(HttpMethod.Head, requestUri); responseMsg = client.SendAsync(rqstMsg).Result; } else { //Note: Need to explicitly specify the content type here otherwise this call fails. if (OperationMethod == HttpMethod.Put) { responseMsg = client.PutAsync <T>(requestUri, postData, mediaFormatter).Result; } else { responseMsg = client.PostAsync <T>(requestUri, postData, mediaFormatter).Result; } } return(responseMsg); }
public void Convert_WhenValueIsAnyType_CreatesContentNegotiatedResponse() { Dog dog = new Dog(); XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); _context.Configuration.Formatters.Clear(); _context.Configuration.Formatters.Add(formatter); var result = _animalValueConverter.Convert(_context, dog); Assert.Equal(HttpStatusCode.OK, result.StatusCode); var content = Assert.IsType<ObjectContent<Animal>>(result.Content); Assert.Same(dog, content.Value); Assert.Same(formatter, content.Formatter); Assert.Same(_request, result.RequestMessage); }
public void Should_return_OK_when_type_group_is_accepted() { var customXmlFormatter = new XmlMediaTypeFormatter(); customXmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/vnd.webapi.contrib+xml")); configuration.Formatters.Add(customXmlFormatter); var notAcceptableMessageHandler = new NotAcceptableMessageHandler(configuration); var requestMessage = new HttpRequestMessage(HttpMethod.Get, "foo/bar"); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/*")); var response = ExecuteRequest(notAcceptableMessageHandler, requestMessage); response.StatusCode.ShouldEqual(HttpStatusCode.OK); }
public void Negotiate_Returns_Wrapped_Inner_XmlFormatter() { // Arrange MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter(); _mockNegotiator.Setup( n => n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns( new ContentNegotiationResult(expectedFormatter, null)); // Act var result = ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]); // Assert Assert.IsType<XmlMediaTypeFormatterTracer>(result.Formatter); }
private static void TestChanging(Action <MediaTypeFormatterCollection> mutation, int expectedCount) { // Arrange MediaTypeFormatter formatter1 = new XmlMediaTypeFormatter(); MediaTypeFormatter formatter2 = new JsonMediaTypeFormatter(); MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[] { formatter1, formatter2 }); int changeCount = 0; collection.Changing += (source, args) => { changeCount++; }; // Act mutation(collection); //Assert Assert.Equal(expectedCount, changeCount); }
public void Negotiate_Traces_BeginEnd_When_Inner_Throws() { // Arrange MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter(); InvalidOperationException expectedException = new InvalidOperationException("test"); _mockNegotiator.Setup( n => n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>())).Throws(expectedException); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End } }; // Act & Assert Assert.Throws<InvalidOperationException>(() => ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0])); // Assert Assert.Equal<TraceRecord>(expectedTraces, _traceWriter.Traces, new TraceRecordComparer()); Assert.Same(expectedException, _traceWriter.Traces[1].Exception); }
public void Negotiate_Traces_BeginEnd() { // Arrange MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter(); _mockNegotiator.Setup( n => n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns( new ContentNegotiationResult(expectedFormatter, null)); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]); // Assert Assert.Equal<TraceRecord>(expectedTraces, _traceWriter.Traces, new TraceRecordComparer()); }
public void Negotiate_Throws_When_Inner_Throws() { // Arrange MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter(); InvalidOperationException expectedException = new InvalidOperationException("test"); _mockNegotiator.Setup( n => n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>())).Throws(expectedException); // Act & Assert InvalidOperationException actualException = Assert.Throws<InvalidOperationException>(() => ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0])); // Assert Assert.Same(expectedException, actualException); }
public void HttpError_Roundtrips_WithXmlSerializer() { HttpError error = new HttpError("error") { { "ErrorCode", 42 }, { "Data", new[] { "a", "b", "c" } } }; MediaTypeFormatter formatter = new XmlMediaTypeFormatter() { UseXmlSerializer = true }; MemoryStream stream = new MemoryStream(); formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null).Wait(); stream.Position = 0; HttpError roundtrippedError = formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null).Result as HttpError; Assert.NotNull(roundtrippedError); Assert.Equal("error", roundtrippedError.Message); Assert.Equal("42", roundtrippedError["ErrorCode"]); Assert.Equal("a b c", roundtrippedError["Data"]); }
public void HttpErrorForInnerException_Serializes_WithXmlSerializer() { HttpError error = new HttpError(new ArgumentException("error", new Exception("innerError")), includeErrorDetail: true); MediaTypeFormatter formatter = new XmlMediaTypeFormatter() { UseXmlSerializer = true }; MemoryStream stream = new MemoryStream(); formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null).Wait(); stream.Position = 0; string serializedError = new StreamReader(stream).ReadToEnd(); Assert.NotNull(serializedError); Assert.Equal( "<Error><Message>An error has occurred.</Message><ExceptionMessage>error</ExceptionMessage><ExceptionType>System.ArgumentException</ExceptionType><StackTrace /><InnerException><Message>An error has occurred.</Message><ExceptionMessage>innerError</ExceptionMessage><ExceptionType>System.Exception</ExceptionType><StackTrace /></InnerException></Error>", serializedError); }
public void BindWithFormatter_Formatters_and_Validator() { HttpParameterDescriptor param = CreateParameterDescriptor(); IBodyModelValidator bodyModelValidator = new Mock<IBodyModelValidator>().Object; MediaTypeFormatter formatter1 = new XmlMediaTypeFormatter(); MediaTypeFormatter formatter2 = new JsonMediaTypeFormatter(); FormatterParameterBinding binding = (FormatterParameterBinding) param.BindWithFormatter(new List<MediaTypeFormatter> { formatter1, formatter2 }, bodyModelValidator); Assert.NotNull(binding); Assert.Equal(bodyModelValidator, binding.BodyModelValidator); MediaTypeFormatter[] formatters = binding.Formatters.ToArray(); Assert.Equal(2, formatters.Length); Assert.Equal(formatter1, formatters[0]); Assert.Equal(formatter2, formatters[1]); }
public void MediaTypeFormatterCollection_Changing_FiresOnSet() { TestChanging((collection) => collection[0] = new XmlMediaTypeFormatter(), 1); }
public void CreateResponse_DoingConneg_PerformsContentNegotiationAndCreatesContentUsingResults() { // Arrange var context = new DefaultHttpContext(); var formatter = new XmlMediaTypeFormatter(); var contentNegotiator = new Mock<IContentNegotiator>(); contentNegotiator .Setup(c => c.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>())) .Returns(new ContentNegotiationResult(formatter, mediaType: null)); context.RequestServices = CreateServices(contentNegotiator.Object, formatter); var request = CreateRequest(context); // Act var response = request.CreateResponse<string>(HttpStatusCode.NoContent, "42"); // Assert Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Same(request, response.RequestMessage); var objectContent = Assert.IsType<ObjectContent<string>>(response.Content); Assert.Equal("42", objectContent.Value); Assert.Same(formatter, objectContent.Formatter); }
public void BindWithFormatter_Formatter_IEnumerable() { HttpParameterDescriptor param = CreateParameterDescriptor(); MediaTypeFormatter formatter1 = new XmlMediaTypeFormatter(); MediaTypeFormatter formatter2 = new JsonMediaTypeFormatter(); FormatterParameterBinding binding = (FormatterParameterBinding) param.BindWithFormatter(new List<MediaTypeFormatter> { formatter1, formatter2 }); Assert.NotNull(binding); MediaTypeFormatter[] formatters = binding.Formatters.ToArray(); Assert.Equal(2, formatters.Length); Assert.Equal(formatter1, formatters[0]); Assert.Equal(formatter2, formatters[1]); }
public void CreateResponse_DoingConneg_PerformsContentNegotiationAndCreatesContentUsingResults() { // Arrange XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); _negotiatorMock.Setup(r => r.Negotiate(typeof(string), _request, _config.Formatters)) .Returns(new ContentNegotiationResult(formatter, null)); _config.Services.Replace(typeof(IContentNegotiator), _negotiatorMock.Object); // Act var response = _request.CreateResponse<string>(HttpStatusCode.NoContent, "42", _config); // Assert Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Same(_request, response.RequestMessage); var objectContent = Assert.IsType<ObjectContent<string>>(response.Content); Assert.Equal("42", objectContent.Value); Assert.Same(formatter, objectContent.Formatter); }
static void Main(string[] args) { // Prompt user for media type Console.WriteLine("Select media type: {1} Xml, {2} Json, {3} Protobuf"); int selection = int.Parse(Console.ReadLine()); // Configure accept header and media type formatter MediaTypeFormatter formatter; string acceptHeader; switch (selection) { case 1: formatter = new XmlMediaTypeFormatter(); ((XmlMediaTypeFormatter)formatter).XmlPreserveReferences (typeof(Category), typeof(List<Product>)); acceptHeader = "application/xml"; break; case 2: formatter = new JsonMediaTypeFormatter(); ((JsonMediaTypeFormatter)formatter).JsonPreserveReferences(); acceptHeader = "application/json"; break; case 3: formatter = new ProtoBufFormatter(); ((ProtoBufFormatter)formatter).ProtobufPreserveReferences (typeof(Category).Assembly.GetTypes()); acceptHeader = "application/x-protobuf"; break; default: Console.WriteLine("Invalid selection: {0}", selection); return; } // Set base address to optionally use Fiddler Console.WriteLine("\nUse Fiddler?"); bool useFiddler = Console.ReadLine().ToUpper() == "Y"; string address = string.Format("http://localhost{0}:51258/api/", useFiddler ? ".fiddler" : string.Empty); // Create an http client with service base address var client = new HttpClient { BaseAddress = new Uri(address) }; // Set request accept header client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); // Get values response HttpResponseMessage response = client.GetAsync("customers").Result; response.EnsureSuccessStatusCode(); // Read response content as string array var customers = response.Content.ReadAsAsync<List<Customer>> (new[] { formatter }).Result; foreach (var c in customers) { Console.WriteLine("{0} {1} {2} {3}", c.CustomerId, c.CompanyName, c.City, c.Country); } // Get customer orders Console.WriteLine("\nCustomer Id:"); string customerId = Console.ReadLine(); response = client.GetAsync("orders?customerId=" + customerId).Result; response.EnsureSuccessStatusCode(); // Read response content var orders = response.Content.ReadAsAsync<List<Order>> (new[] { formatter }).Result; foreach (var o in orders) { PrintOrderWithDetails(o); } // Create a new order Console.WriteLine("\nPress Enter to create a new order"); Console.ReadLine(); var newOrder = new Order { CustomerId = customerId, OrderDate = DateTime.Today, ShippedDate = DateTime.Today.AddDays(1), OrderDetails = new List<OrderDetail> { new OrderDetail { ProductId = 1, Quantity = 5, UnitPrice = 10 }, new OrderDetail { ProductId = 2, Quantity = 10, UnitPrice = 20 }, new OrderDetail { ProductId = 4, Quantity = 40, UnitPrice = 40 } } }; // Post the new order response = client.PostAsync("orders", newOrder, formatter).Result; response.EnsureSuccessStatusCode(); var order = response.Content.ReadAsAsync<Order>(new[] { formatter }).Result; PrintOrderWithDetails(order); // Update the order date Console.WriteLine("\nPress Enter to update order date"); Console.ReadLine(); order.OrderDate = order.OrderDate.GetValueOrDefault().AddDays(1); // Put the updated order response = client.PutAsync("orders", order, formatter).Result; response.EnsureSuccessStatusCode(); order = response.Content.ReadAsAsync<Order>(new[] { formatter }).Result; PrintOrderWithDetails(order); // Delete the order Console.WriteLine("\nPress Enter to delete the order"); Console.ReadLine(); // Send delete response = client.DeleteAsync("Orders/" + order.OrderId).Result; response.EnsureSuccessStatusCode(); // Verify delete response = client.GetAsync("Orders/" + order.OrderId).Result; if (!response.IsSuccessStatusCode) Console.WriteLine("Order deleted"); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); }
/// <summary> /// 创建MediaTypeFormatter /// </summary> /// <param name="mediaType"></param> /// <returns></returns> private MediaTypeFormatter CreateMediaTypeFormatter(string mediaType = MediaType.json) { MediaTypeFormatter mediaTypeFormatter = null; switch (mediaType) { case MediaType.form: mediaTypeFormatter = new FormUrlEncodedMediaTypeFormatter(); break; case MediaType.xml: mediaTypeFormatter = new XmlMediaTypeFormatter(); break; case MediaType.json: default: mediaTypeFormatter = new JsonMediaTypeFormatter(); break; } return mediaTypeFormatter; }
public void HttpErrorWithWhitespace_Roundtrips_WithXmlFormatter() { string message = " foo\n bar \n "; HttpError error = new HttpError(message); MediaTypeFormatter formatter = new XmlMediaTypeFormatter(); MemoryStream stream = new MemoryStream(); formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null).Wait(); stream.Position = 0; HttpError roundtrippedError = formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null).Result as HttpError; Assert.NotNull(roundtrippedError); Assert.Equal(message, roundtrippedError.Message); }
private HttpResponseMessage GetReturnData(ServiceList services) { XmlMediaTypeFormatter xmlFormatter = new XmlMediaTypeFormatter(); xmlFormatter.UseXmlSerializer = true; var content = new ObjectContent<ServiceList>(services, xmlFormatter); return new HttpResponseMessage() { Content = content }; }