【发布时间】:2020-08-04 16:11:16
【问题描述】:
我的 ASP.NET Core 应用程序使用“开箱即用”的外部登录身份验证。我想要实现的 - 在 facebook 挑战中,我想包装重定向 url 并将其作为 json 返回以在 jquery 前端使用。但在请求结束后,我在浏览器中看到 500 错误,在应用程序控制台中看到下一个错误:
失败:Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLV651D6KVJC", Request 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
};
});
有什么办法可以让它工作吗?
【问题讨论】:
-
未能解决此问题,因此必须构建大量视图和操作来为 oauth 弹出窗口制作自定义管道作为解决方法。
-
为什么要设置长度,然后分配正文?只需将字节写入 x.Response.Body 而不替换它。之所以说 0,是因为您替换了正文并且没有对实际响应(原始正文)写任何内容
-
@davidfowl 不记得为什么了,可能我使用了一些其他代码 sn-p 在这里找到。但你是对的,谢谢。
标签: c# asp.net-core kestrel-http-server asp.net-authentication