Home > database >  How can I validate an HTTP response?
How can I validate an HTTP response?

Time:05-07

I'm creating a low level HTTP server and I want to validate that my responses are correct.

Some of them are fine, but others fail. I have saved some responses as bytes and viewing them in HxD, and they look correct, but they obviously aren't in some way.

Here's the start of one HTTP response formatted as hex:

48 54 54 50 2F 31 2E 31 20 32 30 30 20 4F 4B 0D 0A 43 4F 4E 54 45 4E 54 2D 54 59 50 45 3A 20 69 6D 61 67 65 2F 70 6E 67 0D 0A 4C 41 53 54 2D 4D 4F 44 49 46 49 45 44 3A 20 53 75 6E 2C 20 30 31 20 4D 61 79 20 32 30 32 32 20 32 32 3A 32 34 3A 32 34 20 47 4D 54 0D 0A 41 43 43 45 50 54 2D 52 41 4E 47 45 53 3A 20 62 79 74 65 73 0D 0A 45 54 41 47 3A 20 22 37 35 37 35 35 33 36 61 61 35 64 64 38 31 3A 30 22 0D 0A 53 45 52 56 45 52 3A 20 4D 69 63 72 6F 73 6F 66 74 2D 49 49 53 2F 31 30 2E 30 0D 0A 58 2D 50 4F 57 45 52 45 44 2D 42 59 3A 20 41 53 50 2E 4E 45 54 0D 0A 44 41 54 45 3A 20 57 65 64 2C 20 30 34 20 4D 61 79 20 32 30 32 32 20 30 39 3A 30 31 3A 34 38 20 47 4D 54 0D 0A 43 4F 4E 54 45 4E 54 2D 4C 45 4E 47 54 48 3A 20 39 38 37 35 37 0D 0A 43 6F 6E 6E 65 63 74 69 6F 6E 3A 20 63 6C 6F 73 65 0D 0A 0D 0A 0D 0A 89 50 4E 47

How can I validate that the response I'm creating is valid according to RFC 2616?

I'm working in .NET but I don't mind if it's an online tool or a different platform.

Edit:

I've solved my issue with this particular example (3 crlfs instead of 2 between head and body) but I'd still like to know how I can validate these requests automatically.

CodePudding user response:

I ended up achieving this with this nuget package and the following code:

    if (System.Diagnostics.Debugger.IsAttached)
    {
        using (var handler = new HttpParserDelegate())
        using (var parser = new HttpCombinedParser(handler))
        {
            parser.Execute(arr);
        }

        if (!handler.HttpRequestResponse.IsEndOfMessage)
        {
            System.Diagnostics.Debugger.Break();
            throw new InvalidOperationException($"An HTTP response was serialized but it is not a valid response");
        }
    }
  •  Tags:  
  • http
  • Related