public static void RespondToGetRequestWithDelegatingHandler() { // Now we can create an `HttpHandler` to return a response of `"Hello, world!"`. // `HttpMessageHandler`s always return a `Task<'T>` from the `SendAsync` method, // but since we don't need the async response, we'll just use `TaskCompletionSource`. var handler = new DelegateHandler(request => { var response = new HttpResponseMessage { Content = new StringContent("Hello, world!") }; var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(response); return tcs.Task; }); // Set up the configuration for the server. var config = new HttpConfiguration(); // Add our message handler to the configuration. config.MessageHandlers.Add(handler); // Create the server and set its configuration and the message handler. // Note that the HttpServer ctor also takes a message handler, // but that handler changes how the server behaves. We'll use the var server = new HttpServer(config); // Create an `HttpClient` that will send directly to the `server`. var client = new HttpClient(server); // Now send a GET request from the client to retrieve the result. using (var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/api/test")) { var response = client.SendAsync(request, Core.Cts.Token).Result; var body = response.Content.ReadAsStringAsync().Result; Helpers.AssertEquality(Helpers.__, body); } Core.Reset(); }
static void AddHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> f) { var handler = new DelegateHandler(f); Core.Config.MessageHandlers.Add(handler); Core.Config.Routes.MapHttpRoute("Api", "api"); }
// TODO: Other methods, such as PostAsync, etc. // We'll use message handlers to create koan-specific request handlers for each of the following koans. // This option is the best for preventing collisions with the existing controller types, and it lets us // specifically set the expectation within each koan. We'll define a helper here to return an instance // of the `AsyncHandler` we saw in AboutMessageHandlers. static void AddHandler(HttpConfiguration config, Func<HttpRequestMessage, HttpResponseMessage> f) { var handler = new DelegateHandler(f); config.MessageHandlers.Add(handler); config.Routes.MapHttpRoute("Api", "api"); }