无法在Web Api Response中设置Content-MD5标头

时间:2014-03-07 17:15:10

标签: c# asp.net-web-api response

当我尝试设置Content-MD5时 - 标题我得到此异常

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我希望您能帮助我。

2 个答案:

答案 0 :(得分:6)

或者你甚至可以使用为此目的明确设计的header属性。不需要神奇的字符串。

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

答案 1 :(得分:2)

您可以使用Headers.AddWithoutValidation("Content-MD5", hash)(请参阅http://msdn.microsoft.com/en-us/library/hh204926%28v=vs.110%29获取完整的方法说明)使其接受标头而不尝试验证它是否应该在请求或响应上,这是什么现在正在发生。