public void ArtifactScenario_GetArtifactsFromXY_Json() { string baseAddress = string.Format("http://localhost:{0}", GetNextPortNumber()); using (HttpServiceHost host = CreateHttpServiceHost(typeof(ArtifactService), baseAddress)) { host.Open(); using (HttpClient client = new HttpClient()) { client.Channel = new WebRequestChannel(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, baseAddress + "/Artifacts/5,6"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json")); using (HttpResponseMessage response = client.Send(request)) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "status code not ok"); Artifact[] artifacts = DeserializeArtifactsJson(response); Assert.AreEqual(2, artifacts.Length, "Expected 2 artifacts at pos 5,6"); foreach (Artifact artifact in artifacts) { Assert.AreEqual(5, artifact.GridPosition.X, "gridX should be 5"); Assert.AreEqual(6, artifact.GridPosition.Y, "gridY should be 5"); } } } } }
public void NoDuplicateHelpOperationByDefault() { string address = "http://localhost:8080/helpService"; HttpServiceHost host = new HttpServiceHost(typeof(HelpService), new Uri(address)); host.AddDefaultEndpoints(); host.Open(); // this should not throw by default. see CDSMain 196212 }
private static HttpEndpoint[] GetEndpointsFromServiceHost(Type serviceType, Uri uri) { HttpServiceHost host = new HttpServiceHost(serviceType, uri); host.AddDefaultEndpoints(); return(host.Description.Endpoints.OfType <HttpEndpoint>().ToArray()); }
public static void Run() { var config = new HttpConfiguration(); config.RequestHandlers += (coll, ep, desc) => { if ( desc.Attributes.Any(a => a.GetType() == typeof(JsonExtractAttribute)) ) { coll.Add(new JsonExtractHandler(desc)); } }; using (var sh = new HttpServiceHost(typeof(TheService), config, "http://localhost:8080")) { sh.Open(); Console.WriteLine("host is opened"); var client = new HttpClient(); dynamic data = new JsonObject(); data.x = "a string"; data.y = "13"; data.z = "3.14"; var resp = client.PostAsync("http://localhost:8080/v2", new ObjectContent <JsonValue>(data, "application/json")).Result; Console.WriteLine(resp.StatusCode); } }
public static void Run() { var conf = new HttpConfiguration { RequestHandlers = (coll, ep, desc) => { if ( desc.InputParameters.Any( p => p.ParameterType == typeof(IPrincipal))) { coll.Add(new PrincipalFromSecurityContext()); } } } .EnableAuthorizeAttribute(); using (var host = new HttpServiceHost(typeof(TheService), conf, new string[0])) { var ep = host.AddHttpEndpoint(typeof(TheService), "https://localhost:8435/greet"); ep.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new MyCustomValidator(); host.Open(); Console.WriteLine("Service is opened at {0}, press any key to continue", ep.Address); Console.ReadKey(); } }
public static void Main(string[] args) { string serviceURI = ConfigurationManager.AppSettings["ServiceURI"]; HttpServiceHost host = new HttpServiceHost(typeof(RESTBlogsService), serviceURI); try { host.Open(); Console.WriteLine("Service is running..."); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("HttpServiceHost failed to open {0}", ex); } finally { if (host.State == CommunicationState.Faulted) { host.Abort(); } else { host.Close(); } } }
public static ServiceHost CreateWebHost <T>(bool asynchronousSendEnabled, bool faultDetail, bool streamed, HttpMessageHandlerFactory httpMessageHandlerFactory) where T : TestWebServiceBase { var webHost = new HttpServiceHost(typeof(T), TestServiceCommon.ServiceAddress); webHost.AddDefaultEndpoints(); if (faultDetail && webHost.Description.Behaviors.Contains(typeof(ServiceDebugBehavior))) { var debug = webHost.Description.Behaviors[typeof(ServiceDebugBehavior)] as ServiceDebugBehavior; debug.IncludeExceptionDetailInFaults = true; } foreach (HttpEndpoint endpoint in webHost.Description.Endpoints.OfType <HttpEndpoint>()) { endpoint.HelpEnabled = true; endpoint.MessageHandlerFactory = httpMessageHandlerFactory; endpoint.Behaviors.Add(new DispatcherSynchronizationBehavior { AsynchronousSendEnabled = asynchronousSendEnabled }); if (streamed) { endpoint.TransferMode = TransferMode.Streamed; } } webHost.Open(); return(webHost); }
public void ArtifactScenario_GetArtifactsFromXY_Json_MediaRange() { string baseAddress = string.Format("http://localhost:{0}", GetNextPortNumber()); MediaTypeHeaderValue range = new MediaTypeHeaderValue("text/*"); MediaTypeHeaderValue mapsToMediaType = new MediaTypeHeaderValue("text/json"); using (HttpServiceHost host = CreateHttpServiceHost(typeof(ArtifactService), baseAddress, range, mapsToMediaType)) { HttpEndpoint endPoint = host.Description.Endpoints.OfType <HttpEndpoint>().Single(); // Add a media range mapping to map text/* to text/json //endPoint.MediaTypeMappings.Add(new MediaRangeMapping("text/*", "text/json")); host.Open(); using (HttpClient client = new HttpClient()) { client.Channel = new WebRequestChannel(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, baseAddress + "/Artifacts/5,6"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/*")); using (HttpResponseMessage response = client.Send(request)) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "status code not ok"); Artifact[] artifacts = DeserializeArtifactsJson(response); Assert.AreEqual(2, artifacts.Length, "Expected 2 artifacts at pos 5,6"); foreach (Artifact artifact in artifacts) { Assert.AreEqual(5, artifact.GridPosition.X, "gridX should be 5"); Assert.AreEqual(6, artifact.GridPosition.Y, "gridY should be 5"); } } } } }
public void ArtifactScenario_GetArtifactsFoundBy() { string baseAddress = string.Format("http://localhost:{0}", GetNextPortNumber()); using (HttpServiceHost host = CreateHttpServiceHost(typeof(ArtifactService), baseAddress)) { host.Open(); using (HttpClient client = new HttpClient()) { client.Channel = new WebRequestChannel(); using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, baseAddress + "/Artifacts/Rebecca")) { // Put sample data in the request header to demonstrate how service can acccess it request.Headers.Add("Artifacts", "SampleHeaderData"); using (HttpResponseMessage response = client.Send(request)) //client.Get(baseAddress + "/Artifacts/Rebecca")) { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "status code not ok"); Artifact[] artifacts = DeserializeArtifactsDataContract(response); Assert.AreEqual(1, artifacts.Length, "Expected 1 artifact found by Rebecca"); Assert.AreEqual("Rebecca", artifacts[0].FoundBy, "Rebecca should have been the finder"); // Prove the request/response headers were used by the service IEnumerable <string> headerValues = null; bool hadHeader = response.Headers.TryGetValues("Artifacts", out headerValues); Assert.IsTrue(hadHeader, "Failed to write responseHeaders"); Assert.IsTrue(headerValues.Contains("SampleHeaderData"), "Did not copy responseHeaders correctly"); } } } } }
/// <summary> /// Initializes a new instance of the <see cref="HttpWebService<TService>"/> class. /// </summary> /// <param name="serviceBaseUrl">The service base URL without the resource path, such as "http://localhost:2000".</param> /// <param name="serviceResourcePath">The service resource path, such as "products".</param> /// <param name="configuration">The configuration for the service.</param> public HttpWebService(string serviceBaseUrl, string serviceResourcePath, IHttpHostConfigurationBuilder configuration) { this.BaseUri = new Uri(serviceBaseUrl); this.serviceUri = new Uri(new Uri(serviceBaseUrl), serviceResourcePath); this.serviceHost = new HttpConfigurableServiceHost(typeof(TService), configuration, this.serviceUri); this.serviceHost.Open(); }
/// <summary> /// Creates a new <see cref="HttpServiceHost"/> instance. /// </summary> /// <param name="serviceType">Specifies the type of service to host.</param> /// <param name="baseAddresses">The base addresses for the service hosted.</param> /// <returns>A new <see cref="HttpServiceHost"/> instance.</returns> protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { HttpServiceHost host = new HttpServiceHost(serviceType, baseAddresses); host.MessageHandlerFactory = this.MessageHandlerFactory; host.OperationHandlerFactory = this.OperationHandlerFactory; return host; }
public static void Run() { using (var host = new HttpServiceHost(typeof(TheService), "http://localhost:8080/upload")) { host.Open(); Console.WriteLine("Host opened at {0}", host.Description.Endpoints[0].Address); Console.ReadKey(); } }
/// <summary> /// Creates a new <see cref="HttpServiceHost"/> instance. /// </summary> /// <param name="serviceType">Specifies the type of service to host.</param> /// <param name="baseAddresses">The base addresses for the service hosted.</param> /// <returns>A new <see cref="HttpServiceHost"/> instance.</returns> protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { HttpServiceHost host = new HttpServiceHost(serviceType, baseAddresses); host.MessageHandlerFactory = this.MessageHandlerFactory; host.OperationHandlerFactory = this.OperationHandlerFactory; return(host); }
private static HttpServiceHost CreateHttpServiceHost(Type serviceType, string baseAddress) { HttpServiceHost host = new HttpServiceHost(serviceType, new Uri(baseAddress)); host.AddDefaultEndpoints(); HttpEndpoint endpoint = host.Description.Endpoints.OfType <HttpEndpoint>().Single(); endpoint.OperationHandlerFactory = new ArtifactHttpOperationHandlerFactory(new MediaTypeFormatter[0]); return(host); }
public void WhenPostingAPersonThenResponseIndicatesPersonWasAdded() { HelloResource.Initialize(new List <string>()); using (var host = new HttpServiceHost(typeof(HelloResource), this.hostUri)) { host.Open(); var client = new HttpClient(); var response = client.Post(this.hostUri, new StringContent("person=Glenn", Encoding.UTF8, "application/x-www-form-urlencoded")); Assert.AreEqual("Added Glenn", response.Content.ReadAsString()); } }
public static void Run() { var config = new OverrideUriConfiguration <TheService>() .Map("add/{a}/{b}", s => s.Add(default(int), default(int))); using (var host = new HttpServiceHost(typeof(TheService), config, "http://localhost:8080/")) { host.Open(); Console.WriteLine("Host opened at {0}", host.Description.Endpoints[0].Address); Console.ReadKey(); } }
static void HostWithHttpsAndNoneClientCredential() { using (var host = new HttpServiceHost(typeof(TheResourceClass), new string[0])) { var binding = new HttpBinding(HttpBindingSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; host.AddServiceEndpoint(typeof(TheResourceClass), binding, "https://localhost:8435/greet"); host.Open(); Console.WriteLine("Service is opened, press any key to continue"); Console.ReadKey(); } }
public void WhenPostingContactThenResponseStatusCodeIsCreated() { HttpResponseMessage response = null; using (var host = new HttpServiceHost(typeof(ContactsResource), contactsUri)) { host.Open(); var client = new HttpClient(); response = client.Post(contactsUri, this.xmlPostContactContent); } Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); }
private static HttpServiceHost CreateHttpServiceHost(Type serviceType, string baseAddress, MediaTypeHeaderValue range, MediaTypeHeaderValue mediaType) { HttpServiceHost host = new HttpServiceHost(serviceType, new Uri(baseAddress)); host.AddDefaultEndpoints(); HttpEndpoint endpoint = host.Description.Endpoints.OfType <HttpEndpoint>().Single(); MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection(); formatters.JsonFormatter.AddMediaRangeMapping(range, mediaType); endpoint.OperationHandlerFactory = new ArtifactHttpOperationHandlerFactory(formatters); return(host); }
static void Main(string[] args) { //using (var host = new HttpServiceHost(typeof(TheServiceClass), "http://localhost:8080/first")) //using (var host = new HttpServiceHost(typeof(TimerResource), "http://localhost:8080/first")) //using (var host = new HttpServiceHost(typeof(ProcessResource), "http://localhost:8080/procs")) using (var host = new HttpServiceHost(new TodoResource(new ToDoMemoryRepository()), "http://localhost:8080/todo")) { host.Open(); ShowEndpointsOf(host); WaitForKey(); } }
public static void Run() { var config = new HttpConfiguration(); config.RequestHandlers = (coll, endpoint, desc) => coll.Add(new TheOperationHandler(desc)); using (var host = new HttpServiceHost(typeof(TheService), config, "http://localhost:8080/conv")) { host.Open(); Console.WriteLine("Host opened at {0}", host.Description.Endpoints[0].Address); Console.ReadKey(); } }
static void HostWithHttpServiceHost() { var instance = new TodoResource(new ToDoMemoryRepository()); using (var host = new HttpServiceHost(instance, "http://localhost:8080/todo")) { host.AddServiceEndpoint(typeof(TodoResource), new HttpBinding(), "http://localhost:8080/todo2"); host.Open(); ShowEndpointsOf(host); WaitForKey(); } }
static void Main(string[] args) { Console.WriteLine("Start Listening..."); HttpServiceHost host = new HttpServiceHost(); var setting = TransferSettingGetter.Get; host.Register(typeof(IExampleService), typeof(ExampleService)); host.Open(setting); Console.WriteLine("Opened"); Console.ReadKey(); }
public void WhenPostingContactAsFormEncodedThenContactIsAddedToRepository() { this.Initialize(); HttpResponseMessage response = null; using (var host = new HttpServiceHost(typeof(ContactsResource), contactsUri)) { host.Open(); var client = new HttpClient(); response = client.Post(contactsUri, this.formUrlEncodedContactContent); } Assert.AreEqual(TestPostedContactName, this.contacts.Last().Name); }
public void WhenGettingContactWithJsonAcceptHeaderThenResponseIsJson() { HttpResponseMessage response = null; using (var host = new HttpServiceHost(typeof(ContactResource), contactUri)) { host.Open(); var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); response = client.Get(contactGetUri); } response.HasContentWithMediaType("application/json"); }
public static void Run() { using (var host = new HttpServiceHost(typeof(TheService), "http://localhost:8080/async")) { host.AddDefaultEndpoints(); var b = host.Description.Endpoints[0].Binding as HttpBinding; b.MaxBufferSize = 1 * 1024 * 1024; b.MaxReceivedMessageSize = 1 * 1024 * 1024; b.TransferMode = TransferMode.Streamed; host.Open(); Console.WriteLine("Host opened at {0}", host.Description.Endpoints[0].Address); Console.ReadKey(); } }
private static HttpEndpoint[] GetEndpointsFromServiceHostOpen(Type serviceType, Uri uri) { HttpServiceHost host = new HttpServiceHost(serviceType, uri); try { host.Open(); } catch (AddressAlreadyInUseException) { // currently necessary to recover from failed attempt to open port 80 again } return(host.Description.Endpoints.OfType <HttpEndpoint>().ToArray()); }
public void WhenGettingThenReturnsListOfPeopleAdded() { var peopleToSayHelloTo = new List <string>(); peopleToSayHelloTo.Add("Glenn"); HelloResource.Initialize(peopleToSayHelloTo); using (var host = new HttpServiceHost(typeof(HelloResource), this.hostUri)) { host.Open(); var client = new HttpClient(); var response = client.Get(this.hostUri); Assert.AreEqual("Hello Glenn", response.Content.ReadAsString()); host.Close(); } }
public void WhenGettingContactsAsXmlThenCanReadContacts() { Initialize(); HttpResponseMessage response = null; using (var host = new HttpServiceHost(typeof(ContactsResource), contactsUri)) { host.Open(); var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); response = client.Get(contactsUri); } var readContacts = response.Content.ReadAs <Contact[]>(); Assert.AreEqual(1, readContacts.Count()); Assert.AreEqual(TestContactName, readContacts.First().Name); }
private static HttpBehavior[] GetBehaviorsFromServiceHost(Type serviceType, Uri uri) { HttpServiceHost host = new HttpServiceHost(serviceType, uri); host.AddDefaultEndpoints(); List <HttpBehavior> foundBehaviors = new List <HttpBehavior>(); foreach (var endpoint in host.Description.Endpoints) { foreach (var behavior in endpoint.Behaviors.OfType <HttpBehavior>()) { foundBehaviors.Add(behavior); } } return(foundBehaviors.ToArray()); }
public static void Run() { var config = new HttpConfiguration() .UseParameterConverterFor <AComplexType>(s => new AComplexType { Value = s.ToUpper() }) .UseParameterConverterFor <AnotherComplexType>(s => new AnotherComplexType { Value = Int32.Parse(s) + 1 }); using (var host = new HttpServiceHost(typeof(TheService), config, "http://localhost:8080/conv")) { host.Open(); Console.WriteLine("Host opened at {0}", host.Description.Endpoints[0].Address); var client = new HttpClient(); Console.WriteLine(client.GetAsync("http://localhost:8080/conv/hello/3").Result.Content.ReadAsStringAsync().Result); } }
private static ServiceHost GetHttpServiceHost(Type serviceType, out string baseAddress) { Tuple<ServiceHost, string> serviceHostData = null; if (!serviceTypeToHttpServiceHostMapping.TryGetValue(serviceType, out serviceHostData)) { ServiceHost host = null; baseAddress = null; while (host == null) { try { baseAddress = string.Format("http://localhost:{0}", GetNextPortNumber()); host = new HttpServiceHost(serviceType, new Uri(baseAddress)); HttpBehavior behavior = host.AddDefaultEndpoints()[0].Behaviors.Find<HttpBehavior>(); behavior.HelpEnabled = true; host.Open(); } catch (AddressAlreadyInUseException) { host = null; } catch (UriFormatException) { host = null; } } serviceHostData = new Tuple<ServiceHost, string>(host, baseAddress); if (!serviceTypeToHttpServiceHostMapping.TryAdd(serviceType, serviceHostData)) { host.Close(); return GetHttpServiceHost(serviceType, out baseAddress); } } baseAddress = serviceHostData.Item2; return serviceHostData.Item1; }
private static HttpEndpoint[] GetEndpointsFromServiceHost(Type serviceType, Uri uri) { HttpServiceHost host = new HttpServiceHost(serviceType, uri); host.AddDefaultEndpoints(); return host.Description.Endpoints.OfType<HttpEndpoint>().ToArray(); }
private static HttpEndpoint[] GetEndpointsFromServiceHostOpen(Type serviceType, Uri uri) { HttpServiceHost host = new HttpServiceHost(serviceType, uri); try { host.Open(); } catch (AddressAlreadyInUseException) { // currently necessary to recover from failed attempt to open port 80 again } return host.Description.Endpoints.OfType<HttpEndpoint>().ToArray(); }
private static HttpBehavior[] GetBehaviorsFromServiceHost(Type serviceType, Uri uri) { HttpServiceHost host = new HttpServiceHost(serviceType, uri); host.AddDefaultEndpoints(); List<HttpBehavior> foundBehaviors = new List<HttpBehavior>(); foreach (var endpoint in host.Description.Endpoints) { foreach (var behavior in endpoint.Behaviors.OfType<HttpBehavior>()) { foundBehaviors.Add(behavior); } } return foundBehaviors.ToArray(); }
private static HttpBehavior[] GetBehaviorsFromServiceHostOpen(Type serviceType, Uri uri) { HttpServiceHost host = new HttpServiceHost(serviceType, uri); try { host.Open(); } catch (AddressAlreadyInUseException) { // currently necessary to recover from failed attempt to open port 80 again } List<HttpBehavior> foundBehaviors = new List<HttpBehavior>(); foreach (var endpoint in host.Description.Endpoints) { foreach (var behavior in endpoint.Behaviors.OfType<HttpBehavior>()) { foundBehaviors.Add(behavior); } } return foundBehaviors.ToArray(); }