0

I have an API endpoint that has a "hash" key that is sent via the HTTPheader request. When then end point is hit I need to compare the hash key from the header to the hash key on my end point as follows

public async Task<ResponseHandler> test([FromBody] Command command)
{
    if (Request.Headers.ContainsKey("hash") ? Request.Headers.TryGetValue("hash", out var hash) : throw new InvalidOperationException())
    {
        using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes("some key")))
        using (var memoryStream = new MemoryStream()) //fails
        {
            await Request.Body.CopyToAsync(memoryStream);
            memoryStream.Position = 0;
            if (Convert.ToBase64String(hmacsha256.ComputeHash(memoryStream.ToArray())) != hash)
                throw new Exception();
        }
    }
}

but when it hits the memory stream it fails and gives me an error

'memoryStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException' 'memoryStream.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

what am I doing wrong?

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
josh
  • 29
  • 5
  • 1
    Unrelated, but why the `ContainsKey` followed by the `TryGetValue`? That seems redundant. Just do the `TryGetValue`. Also the `if` is pointless, because the thing it's checking will always be `true` (or will throw an exception) – canton7 Jun 09 '20 at 09:26
  • What does the exception's _message_ say? – René Vogt Jun 09 '20 at 09:27
  • @RenéVogt it just returns "Exception of type 'System.Exception' was thrown." in postman – josh Jun 09 '20 at 09:29
  • How about setting a breakpoint or adding a `try/catch` block to investigate the exception details? – René Vogt Jun 09 '20 at 09:31
  • @RenéVogt i added a try an catch around the memory stream and the exception still returns ""Exception of type 'System.Exception' was thrown."" – josh Jun 09 '20 at 09:36
  • I'm confused, the exception you posted is an `InvalidOperationException`, but you always talk about the base `Exception`. An exception has a `Message` property that can tell you more, but therefor you need to catch it or have a breakpoint and _debug_ your code. Are you _sure_ that it is the marked line that throws the exception? I really doubt that the constructor throws. It seems it's actually the exception you throw yourself after the `Convert.ToBAse64STring()`. – René Vogt Jun 09 '20 at 09:58
  • Please tell us where you are **seeing** those errors? Some debugging features of VS give the appearance of an exception occurring - but they aren't "real". Can you show us a screenshot? – mjwills Jun 09 '20 at 10:01

0 Answers0