我想Request.Body
在 ASP.Net Core 的后台服务中处理 a,所以我首先将它添加到 ConcurrentQueue。
public class BackgroundJobs
{
public ConcurrentQueue<Stream> Queue { get; set; } = new ConcurrentQueue<Stream>();
}
concurrentQueueAddSingleton
在 Startup.cs 中被实例化
[ApiController]
public class NotificationsController : ControllerBase
{
private readonly BackgroundJobs backgroundJobs;
public NotificationsController( BackgroundJobs backgroundJobs)
{
this.backgroundJobs = backgroundJobs;
}
//...........
[HttpPost]
public ActionResult<string> Post([FromQuery] string validationToken = null)
{
if (!string.IsNullOrEmpty(validationToken))
{
return Ok(validationToken);
}
else
{
backgroundJobs.Queue.Enqueue(Request.Body);
return Accepted();
}
}
}
BackgroundServices.cs 在 Startup.cs 中用AddHostedService
. 当Request.Body
它在队列中时,我想进一步处理它。
public class BackgroundServices : BackgroundService, IHostedService
{
private readonly BackgroundJobs backgroundJobs;
private IServiceScopeFactory iServiceScopeFactory;
public BackgroundServices(BackgroundJobs backgroundJobs, IServiceScopeFactory iServiceScopeFactory)
{
this.backgroundJobs = backgroundJobs;
this.iServiceScopeFactory = iServiceScopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
Stream stream;
while (!cancellationToken.IsCancellationRequested)
{
if (this.backgroundJobs.Queue.TryDequeue(out stream))
{
StreamReader streamReader = new StreamReader(stream);
string content = await streamReader.ReadToEndAsync();
var list = JsonConvert.DeserializeObject<Notifications>(content)
//......
但是收到string content = await streamReader.ReadToEndAsync()
以下错误消息:System.ObjectDisposedException in System.Private.CoreLib.dll