我使用HttpSelfHostServer来托管我的WebApi。我像这样返回一个PushStreamContent
public HttpResponseMessage Get(HttpRequestMessage request)
{
var response = request.CreateResponse();
response.Content = new PushStreamContent(OnStreamAvailable, "text/eventstream");
return response;
}
在我向我的api发出第二次请求之前,Everthing正在按预期工作。第一个请求是阻止,第二个请求无法到达Get-function,直到我关闭第一个请求。
我已按此设置我的配置
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
config.TransferMode = System.ServiceModel.TransferMode.Streamed;
config.MaxConcurrentRequests = 10;
为什么第一个电话会阻止第二个电话?
修改: 这是我完整的控制器:
public class PushController : ApiController
{
private static readonly ConcurrentBag<StreamWriter> _Writers = new ConcurrentBag<StreamWriter>();
public HttpResponseMessage Get(HttpRequestMessage request)
{
var response = request.CreateResponse();
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Cache-Control", "no-cache, must-revalidate");
response.Content = new PushStreamContent(OnStreamAvailable, "text/event-stream");
return response;
}
private void OnStreamAvailable(Stream stream, HttpContent content, TransportContext context)
{
_Writers.Add(new StreamWriter(stream) { AutoFlush = true });
}
public static void Say(string text)
{
try
{
foreach (var w in _Writers)
{
w.Write("data:{ text : \"" + text + "\" }\n\n");
}
}
catch { }
}
}