【发布时间】:2017-04-24 00:58:19
【问题描述】:
我正在测试 .net core 并使用 .net core + websockets 制作一个小型示例应用程序,以将一些数据推送到我的应用程序中。我想使用 dbcontext 将这些数据保存在数据库中。
但是,我在我的 websocket 处理程序中获取 dbcontext 时遇到问题。那么如何创建要使用的 dbcontext。
我的启动配置方法包含这个:
...
app.Map("/ws", WSHandler.Map);
...
这是我的 WSHandler 类,它实现了从传入连接中实际读取。我需要一个 DbContext,我可以用它来读取/写入数据库。
/// <summary>
/// Handler for an incoming websocket client
/// </summary>
public class WSHandler {
/// <summary>
/// Max size in bytes of an incoming/outgoing message
/// </summary>
public const int BufferSize = 4096;
/// <summary>
/// The socket of the current connection
/// </summary>
WebSocket socket;
/// <summary>
/// Constructor, assign socket to current instance and adds socket to ConnectedClients.
/// </summary>
/// <param name="socket"></param>
WSHandler(WebSocket socket) {
this.socket = socket;
}
/// <summary>
/// Configure app to use websockets and register handler.
/// </summary>
/// <param name="app"></param>
public static void Map(IApplicationBuilder app) {
app.UseWebSockets();
app.Use((WSHandler.Acceptor);
}
/// <summary>
/// Accept HttpContext and handles constructs instance of WSHandler.
/// </summary>
/// <param name="hc">The HttpContext</param>
/// <param name="n">Task n</param>
/// <returns></returns>
static async Task Acceptor(HttpContext hc, Func<Task> n) {
if (hc.WebSockets.IsWebSocketRequest == false) {
return;
}
var socket = await hc.WebSockets.AcceptWebSocketAsync();
var h = new WSHandler(socket);
await h.Loop();
}
/// <summary>
/// Wait's for incoming messages
/// </summary>
/// <returns></returns>
async Task Loop() {
var buffer = new Byte[BufferSize];
ArraySegment<Byte> segment = new ArraySegment<byte>(buffer);
while (this.socket.State == WebSocketState.Open) {
WebSocketReceiveResult result = null;
do {
result = await socket.ReceiveAsync(segment, CancellationToken.None);
} while (result.EndOfMessage == false);
// do something with message here. I want to save parse and save to database
}
}
}
【问题讨论】:
-
嗨,@John Smith。你解决了这个问题吗?我现在正在寻找解决方案
-
@Mergasov 是的,让我去代码,我会发布答案。
标签: c# asp.net entity-framework asp.net-core .net-core