2014-03-07 143 views
1

当我尝试设置Content-MD5 -Header我得到这个例外无法设置内容-MD5标头中的WebAPI响应

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: 

这是例外

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; 
} 

这里的部分是源代码https://bitbucket.org/Knerd/caching-system我希望你能帮助我。

+1

好的,我通过其更改为'Request.Content.Headers.FirstOrDefault(H => h.Key == “内容-MD5”)解决了这个问题' – Knerd

回答

5

或者您甚至可以使用明确设计用于此目的的标题属性。不需要魔术字符串。

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

你可以请检查这个http://stackoverflow.com/questions/26615183/implementing-http-caching-etag-feature-using-md5-in-asp-net-web-api – user960567

相关问题