我的 ASP.NET Core 应用程序使用“开箱即用”的外部登录身份验证。我想要实现的 - 在 facebook 挑战中,我想包装重定向 url 并将其作为 json 返回以在 jquery 前端中使用。但请求结束后,我在浏览器中看到 500 错误,在应用程序控制台中看到下一个错误:
失败:Microsoft.AspNetCore.Server.Kestrel[13]
连接 ID“0HLV651D6KVJC”,请求 ID“0HLV651D6KVJC:00000005”:抛出了未处理的异常
应用。 System.InvalidOperationException:响应内容长度
不匹配:写入的字节太少(470 中的 0)。
我的外部登录操作,没有什么特别值得一看的
[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");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)