gpt4 book ai didi

c# - 响应内容长度不匹配 : too few bytes written

转载 作者:行者123 更新时间:2023-12-03 20:25:50 36 4
gpt4 key购买 nike

我的 ASP.NET Core 应用程序使用“开箱即用”的外部登录身份验证。我想要实现的 - 在 facebook 挑战中,我想包装重定向 url 并将其作为 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
};
});

有什么办法可以让它工作吗?

最佳答案

使用新的 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");

关于c# - 响应内容长度不匹配 : too few bytes written,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61351582/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com