c# - 无法在 WebApi 响应中设置 Content-MD5 header

标签 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: 

这是异常(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;
}

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

最佳答案

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

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

关于c# - 无法在 WebApi 响应中设置 Content-MD5 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22256470/

相关文章:

c# - 异步操作后的 HttpContext.Current.Items

Django 返回大文件

node.js - Node Express res.set() 不起作用

c# - 将日期字符串转换为日期时间

javascript - 使用 Kendo UI 数据源的授权 header 拦截器

支持流式传输的 C# 视频播放器?

asp.net - 返回项、Json(item) 和 Ok(item) 之间的 IHttpActionResult 区别

java - 如何将响应正文时间戳格式更改为 unix 时间戳?

c# - AddPicture 有替代品吗? (C#,Epplus)

c# - User.Identity.IsAuthenticated 始终返回 false