Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Forked from prabirshrestha/Client.cs
Created March 29, 2016 15:18
Show Gist options
  • Save ChrisMcKee/7b07ca31f1f739b4bcea to your computer and use it in GitHub Desktop.
Save ChrisMcKee/7b07ca31f1f739b4bcea to your computer and use it in GitHub Desktop.
Batch Request in nancy
using System.Net.Http;
class Program
{
static void Main(string[] args)
{
var client = new HttpClient();
var batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:3440/api/batch");
var batchContent = new MultipartContent("batch");
batchRequest.Content = batchContent;
batchContent.Add(new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, "http://localhost:3440/api/hello")));
batchContent.Add(new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, "http://localhost:3440/api/world")));
using (var stdout = Console.OpenStandardOutput())
{
Console.WriteLine("<<< REQUEST >>>");
Console.WriteLine();
Console.WriteLine(batchRequest);
Console.WriteLine();
batchContent.CopyToAsync(stdout).Wait();
Console.WriteLine();
var batchResponse = client.SendAsync(batchRequest).Result;
Console.WriteLine("<<< RESPONSE >>>");
Console.WriteLine();
Console.WriteLine(batchResponse);
Console.WriteLine();
batchResponse.Content.CopyToAsync(stdout).Wait();
Console.WriteLine();
Console.WriteLine();
}
Console.ReadKey();
}
}
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Nancy;
public class BatchApiModule : NancyModule
{
public BatchApiModule()
: base("/api")
{
Post["/batch"] =
x =>
{
var contentType = Request.Headers["content-type"].First();
var mimeType = contentType.Split(';').First();
if (mimeType != "multipart/batch")
return 400;
var multipartBoundry = Regex.Match(contentType, @"boundary=(?<token>[^\n\; ]*)").Groups["token"].Value.Replace("\"", "");
if (string.IsNullOrEmpty(multipartBoundry))
return 400;
var multipart = new HttpMultipart(Request.Body, multipartBoundry);
foreach (var boundry in multipart.GetBoundaries())
{
using (var httpRequest = new StreamReader(boundry.Value))
{
// Request req = httpRequest.ReadAsRequest();
var str = httpRequest.ReadToEnd();
}
}
return 200;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment