如何让ASP.NET Core WebAPI在每个API请求中使用一个线程
有没有办法让ASP.NET Core Web API在单独的线程中处理一个请求?
其实确实是多线程的,每个请求一个线程。
我在反序列化传入的请求时确实有问题。The JsonSerializer 在一个独立的线程中运行,我无法访问当前请求。
如果请求/操作是同步执行的,我可以使用线程ID来跟踪当前请求。
为了更清楚地说明我的问题,下面给出一个例子。这是一个依赖注入问题。
// initialization of the request
HandleAuthenticateAsync()
{
this.Request.RouteValues["SomeInfo"] = MyContext;
}
[HttpPost, Route("DoSomeThing"), Authorize("User")]
virtual public AResult DoSomeThing(ComplexType prm)
{
// this.Request is known here
// so I know who called me and have access to my context
var myContext = this.Request.RouteValues["SomeInfo"];
...do something...
return result;
}
// base class to many classes
// needs MyContext to deserialize
[JsonConverter(typeof(MyConverter<ComplexType>))]
public class ComplexType
{
// lazy property
public TypeX Prop1
{
get {
//SomeDependencies of MyContext;
//gets read during deserialization what cause conflicts
}
set { /* do nothing */ }
}
}
// the converter is being called on different thread/task
public class MyConverter<T>
: JsonConverter<T>
{
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// ???????????
// WHERE I AM?
// ???????????
// what action is actually called?
// I need access to MyContext
// the context is thread/request dependent
// how to get access to current request?
// before deserialization I must init some work
// tell what context is actually active.
// deserializer runs on a different thread/task
using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
{
// deserialize to target type
return (T)doc.RootElement.Deserialize(targetType, options);
}
}
//...
}
解决方案
我用AI找到了这个解决方案。
将 MyConverter 从类头部移到服务配置中,并使用上下文访问器。
builder.Services.AddHttpContextAccessor();
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。