In .NET is it possible to convert a raw HTTP request to HTTPWebRequest object?
I\'m sure .NET internally doing it. Any idea which part of the .NET is actually handli
Its possible now, but only with .Net Core 2.0+. Use Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpParser class:
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Text;
public class Program : IHttpRequestLineHandler, IHttpHeadersHandler
{
public static void Main(string[] args)
{
string requestString =
@"POST /resource/?query_id=0 HTTP/1.1
Host: example.com
User-Agent: custom
Accept: */*
Connection: close
Content-Length: 20
Content-Type: application/json
{""key1"":1, ""key2"":2}";
byte[] requestRaw = Encoding.UTF8.GetBytes(requestString);
ReadOnlySequence buffer = new ReadOnlySequence(requestRaw);
HttpParser parser = new HttpParser();
Program app = new Program();
Console.WriteLine("Start line:");
parser.ParseRequestLine(app, buffer, out var consumed, out var examined);
buffer = buffer.Slice(consumed);
Console.WriteLine("Headers:");
parser.ParseHeaders(app, buffer, out consumed, out examined, out var b);
buffer = buffer.Slice(consumed);
string body = Encoding.UTF8.GetString(buffer.ToArray());
Dictionary bodyObject = Newtonsoft.Json.JsonConvert.DeserializeObject>(body);
Console.WriteLine("Body:");
foreach (var item in bodyObject)
Console.WriteLine($"key: {item.Key}, value: {item.Value}");
Console.ReadKey();
}
public void OnHeader(Span name, Span value)
{
Console.WriteLine($"{Encoding.UTF8.GetString(name)}: {Encoding.UTF8.GetString(value)}");
}
public void OnStartLine(HttpMethod method, HttpVersion version, Span target, Span path, Span query, Span customMethod, bool pathEncoded)
{
Console.WriteLine($"method: {method}");
Console.WriteLine($"version: {version}");
Console.WriteLine($"target: {Encoding.UTF8.GetString(target)}");
Console.WriteLine($"path: {Encoding.UTF8.GetString(path)}");
Console.WriteLine($"query: {Encoding.UTF8.GetString(query)}");
Console.WriteLine($"customMethod: {Encoding.UTF8.GetString(customMethod)}");
Console.WriteLine($"pathEncoded: {pathEncoded}");
}
}
Output:
Start line:
method: Post
version: Http11
target: /resource/?query_id=0
path: /resource/
query: ?query_id=0
customMethod:
pathEncoded: False
Headers:
Host: example.com
User-Agent: custom
Accept: */*
Connection: close
Content-Length: 20
Content-Type: application/json
Body:
key: key1, value: 1
key: key2, value: 2