Question

When I try to set the Content-MD5-Header I get this exception

System.InvalidOperationException wurde nicht von Benutzercode behandelt.
  HResult=-2146233079
  Message=Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
  Source=System.Net.Http
  StackTrace:
       bei System.Net.Http.Headers.HttpHeaders.CheckHeaderName(String name)
       bei System.Net.Http.Headers.HttpHeaders.Add(String name, String value)
       bei caching_test.Controllers.ValuesController.Get(Int32 id) in C:\Users\ulbricht\Documents\Bitbucket\caching-system\caching test\Controllers\ValuesController.cs:Zeile 35.
       bei lambda_method(Closure , Object , Object[] )
       bei System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
       bei System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
       bei System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
       bei System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
  InnerException: 

This is the part with the exception

public HttpResponseMessage Get(int id)
{
    var result = "value" + id;
    var hash = Convert.ToBase64String(MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(result)));
    if (Request.Headers.FirstOrDefault(h => h.Key == "Content-MD5").Value != null)
    {
        var hashvalue = Request.Headers.FirstOrDefault(h => h.Key == "Content-MD5").Value.FirstOrDefault();
        if (hashvalue == hash)
        {
            return Request.CreateResponse(HttpStatusCode.NotModified);
        }
    }
    var response = Request.CreateResponse(HttpStatusCode.OK, result);
    response.Headers.Add("Content-MD5", hash); // <------- Here comes the error
    return response;
}

Here is the sourcecode https://bitbucket.org/Knerd/caching-system I hope you can help me.

Was it helpful?

Solution

Or you could even use the header property that is designed explicitly for the purpose. No magic strings required.

response.Content.Headers.ContentMD5 = MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(result));

OTHER TIPS

You can use Headers.AddWithoutValidation("Content-MD5", hash) (see http://msdn.microsoft.com/en-us/library/hh204926%28v=vs.110%29 for the full method description) to make it accept the header without trying to validate it to see if it should be on the request or response, which is what is happening now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top