Reputation: 47
I have the following HttpeRequest Body as Text:
--batch_f1d4b121-35c3-40a0-bbbd-cb1a9f1a5f13
Content-Type: application/http; msgtype=request
POST /api/values HTTP/1.1
Host: localhost:5102
Content-Type: application/json; charset=utf-8
{"value": "Hello World"}
--batch_f1d4b121-35c3-40a0-bbbd-cb1a9f1a5f13
Content-Type: application/http; msgtype=request
PUT /api/values/5 HTTP/1.1
Host: localhost:5102
Content-Type: application/json; charset=utf-8
{"value": "Hello World"}
--batch_f1d4b121-35c3-40a0-bbbd-cb1a9f1a5f13
Content-Type: application/http; msgtype=request
DELETE /api/values/5 HTTP/1.1
Host: localhost:5102
--batch_f1d4b121-35c3-40a0-bbbd-cb1a9f1a5f13--
I tired using regex and I succeed in some and fail in others.
Dose any one manage to parse and split ?
Upvotes: 0
Views: 278
Reputation: 47
I found that I could use MultipartSection to navigate through the batch requests:
var boundry = request.GetMultipartBoundary();
var contentTypeBoundry = request.ContentTypeBoundary();
var requests = new List<HttpRequestMessage>();
var reader = new MultipartReader(boundry, request.Body);
var section = await reader.ReadNextSectionAsync();
while (section!= null)
{
var xBodyAsText= await new StreamReader(section.Body).ReadToEndAsync();
requests.Add(xBodyAsText.ToSimpleHttpRequestMessage());
section = await reader.ReadNextSectionAsync();
}
I have got a solution from ChatGPT:
public static HttpRequestMessage ToSimpleHttpRequestMessage(this string text)
{
var lines = text.Split("\r\n");
var requestLine = lines[0].Split(' ');
var request = new HttpRequestMessage();
request.RequestUri = new Uri("http://" + lines[1].Split(": ")[1] + requestLine[1]);
request.Method = new HttpMethod(requestLine[0]);
if(lines.Length > 4)
{
request.Content = new StringContent(lines[4], Encoding.UTF8, lines[2].Split(": ")[1].Split("; ")[0]);
}
return request;
}
I need better if any one faced something like it.
Upvotes: 0