![](/img/trans.png)
[英]Azure BlobBaseClient.OpenReadAsync() leads to: System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (...)
[英]Response Content-Length mismatch: too few bytes written
我的 ASP.NET 核心應用程序使用“開箱即用”外部登錄身份驗證。 What I want to implement - on facebook challenge I want to wrap redirect url and return it as json to consume in jquery frontend. 但是在請求結束后,我在瀏覽器中看到 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");
更改代碼以寫入原始響應 stream 並且它現在可以工作。
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);
};
你可以使用這樣的東西:
var stream = new MemoryStream();
/// writing to the stream
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
/// then read stream
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.