Теперь это возможно, но только с .Net Core 2.0+.
Используйте 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<byte> buffer = new ReadOnlySequence<byte>(requestRaw);
HttpParser<Program> parser = new HttpParser<Program>();
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<string, int> bodyObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, int>>(body);
Console.WriteLine("Body:");
foreach (var item in bodyObject)
Console.WriteLine($"key: {item.Key}, value: {item.Value}");
Console.ReadKey();
}
public void OnHeader(Span<byte> name, Span<byte> value)
{
Console.WriteLine($"{Encoding.UTF8.GetString(name)}: {Encoding.UTF8.GetString(value)}");
}
public void OnStartLine(HttpMethod method, HttpVersion version, Span<byte> target, Span<byte> path, Span<byte> query, Span<byte> 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}");
}
}
Выход:
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