响应内容长度不匹配:写入的字节太少

Response Content-Length mismatch: too few bytes written

我的 ASP.NET 核心应用程序使用 "out-of-box" 外部登录身份验证。我想要实现的 - 在 facebook 挑战中,我想将重定向 url 和 return 包装为 json 以在 jquery 前端使用。但是请求结束后,我在浏览器中看到 500 错误,在应用程序控制台中看到下一个错误:

fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLV651D6KVJC", Request id "0HLV651D6KVJC:00000005": An unhandled exception was thrown by the application. System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 470).

我的外部登录操作,没有什么特别需要看的

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
    // Request a redirect to the external login provider.
    var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
    var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
    return Challenge(properties, provider);
}

Facebook 身份验证配置:

services.AddAuthentication().AddFacebook(facebookOptions =>
{
    facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
    facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];

    facebookOptions.Events.OnRedirectToAuthorizationEndpoint =
        async (x) =>
        {

            UTF8Encoding encoding = new UTF8Encoding();
            var content = JsonConvert.SerializeObject(new { redirect_url = x.RedirectUri });
            byte[] bytes = encoding.GetBytes(content);

            x.Response.StatusCode = 200;
            x.Response.ContentLength = bytes.Length;
            x.Response.ContentType = "text/plain";
            x.Response.Body = new MemoryStream();

            await x.Response.WriteAsync(content);
            // at this point I see that x.Response.Body.Length == 470, but message states there are 0 of 470 written
        };
});

有什么方法可以让它发挥作用吗?

更改了代码以写入原始响应流,现在可以使用了。

facebookOptions.Events.OnRedirectToAuthorizationEndpoint =
    async (x) =>
    {
        var content = JsonConvert.SerializeObject(new { redirect_url = x.RedirectUri });

        x.Response.StatusCode = 200;
        x.Response.ContentType = "text/plain";

        await x.Response.WriteAsync(content);
    };

使用新的 C# using 语法时也会发生这种情况:

using var ms = new MemoryStream();
using var writer = new StreamWriter(ms);
writer.WriteLine("my content");
memoryStream.Position = 0;
return File(ms, "text/plain");

在这种情况下,MemoryStream 在刷新 StreamWriter 之前被访问。对 StreamWriter:

使用旧语法
using var ms = new MemoryStream();
using (var writer = new StreamWriter(ms, Encoding.UTF8, -1, true))
{
    writer.WriteLine("my content");
}
memoryStream.Position = 0;
return File(ms, "text/plain");

或刷新作者:

using var ms = new MemoryStream();
using var writer = new StreamWriter(ms);
writer.WriteLine("my content");
writer.Flush();
memoryStream.Position = 0;
return File(ms, "text/plain");