我想將我的數據從web API推送到客戶端,所以我在Web API中使用PushStreamContent。 我的數據都是學生存在數據庫中。PushStreamContent Web API
public HttpResponseMessage GetAll()
{
HttpResponseMessage response = new HttpResponseMessage();
var students = _symboleService.GetAll();
response.Content = new PushStreamContent((students, httpContent, context) =>
{
OnStreamAvailable(students, httpContent, context);
}, "text/plain");
return response;
}
private void OnStreamAvailable(Stream stream, HttpContent content,TransportContext context)
{
StreamWriter responseStreamWriter = new StreamWriter(stream);
clients.Add(responseStreamWriter);
}
但錯誤顯示在該線上的「學生」:
response.Content = new PushStreamContent((students, httpContent, context) =>
本地或命名參數「學生」不能在此範圍 聲明,因爲這個名字是在使用包圍本地範圍以限定 本地或參數
更新我在這裏的要點是將數據推送到客戶端, 一些修改後,該我的代碼,但它示出了在線路錯誤時,需要用於非靜態字段
var students = _symboleService.GetAll();
的對象引用,方法或 財產 'SymbolesController._symboleService'
private static readonly Lazy<Timer> _timer = new Lazy<Timer>(() => new Timer(TimerCallback, null, 0, 1000));
private static readonly ConcurrentDictionary<StreamWriter, StreamWriter> _outputs = new ConcurrentDictionary<StreamWriter, StreamWriter>();
public HttpResponseMessage GetAll()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new PushStreamContent((responseStream, httpContent, context) =>
{
StreamWriter responseStreamWriter = new StreamWriter(responseStream);
_outputs.TryAdd(responseStreamWriter, responseStreamWriter);
}, "text/plain");
Timer t = _timer.Value;
return response;
}
// Runs every second after the first request to this controller and
// writes to the response streams of all currently active requests
private static void TimerCallback(object state)
{
foreach (var kvp in _outputs.ToArray())
{
StreamWriter responseStreamWriter = kvp.Value;
try
{
var students = _symboleService.GetAll();
responseStreamWriter.Write(students);
responseStreamWriter.Flush();
}
catch { }
}
}
順便說一句,如果我在這裏改變studentsby DateTime.Now,它的工作原理:
responseStreamWriter.Write(students); to
responseStreamWriter.Write(DateTime.Now);
這聽起來像你試圖實施推送消息範例。你可能想看看SignalR。 http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr –
我看到它晚了,我的代碼差不多完成了,也許我稍後會看到它,thnx – Juste3alfaz