304与Owin的回应

时间:2013-10-29 14:24:19

标签: c# owin

使用Owin中间件做出304响应的正确方法是什么?

我正在做这个

public override Task Invoke(IOwinContext context)
{
    var response = context.Response;
    response.ContentType = "application/javascript";
    response.StatusCode = 200;

    if (ClientCached(context.Request, scriptBuildDate))
    {
        response.StatusCode = 304;
        response.Headers["Content-Length"] = "0";
        return null;
    }
    response.Headers["Last-Modified"] = scriptBuildDate.ToUniversalTime().ToString("r");

    return context.Response.WriteAsync(js);
}

返回null对于空体反应是否正确?它有效,但我想知道它应该如何设置

1 个答案:

答案 0 :(得分:1)

为了完全符合规范,您应该使用Stream.Null,因为这是表示无身体情景的理想方式。

public override Task Invoke(IOwinContext context)
{
    var response = context.Response;
    response.ContentType = "application/javascript";

    if (ClientCached(context.Request, scriptBuildDate))
    {
        response.StatusCode = 304;

        //Close the existing body just in case
        response.Body.Close();
        response.Body = Stream.Null;

        return Task.FromResult<Object>(null);
    }
    else
    {
        response.StatusCode = 200;
        response.Headers["Last-Modified"] = scriptBuildDate.ToUniversalTime().ToString("r");

        return context.Response.WriteAsync(js);
    }
}