我有一个用于存储数据的函数。这些数据在前端进行监控,当有新数据时,我想通知我的前端。 我通过使用 SignalR 实现了这一点,它需要我从函数返回 SignalRMessageAction 而不是典型的 HttpResponseData。
这是有效的,但是我有一些问题和疑问。
我有错误处理中间件,配置为捕获所有自定义异常,但是当我从返回 SignalRMessageAction 的函数抛出异常时,它不会被捕获,并且我的服务器返回 500 而不是有意义的异常。
想象一下,我想要 GET 请求,当触发时,也会通知订阅者并返回请求的数据,而不是 SignalRMessageAction。
这是我现在如何使用它的简化示例。
[Function("StoreGeofenceMessage")]
[SignalROutput(HubName = "myhub")] //Hub name is not actually used anywhere
public async Task<SignalRMessageAction> RunStoreMessage(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "v1/messages")] HttpRequestData req,
FunctionContext executionContext)
{
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
MessageType messageType = data.type;;
int geofenceId = data.geofenceId;
DateTime timestamp = data.timestamp;
var geofenceMessage = new GeofenceMessage(geofenceId, timestamp, messageType);
messagesService.StoreMessage(geofenceMessage);
return new SignalRMessageAction("dashboardUpdate")
{
Arguments = new object[] { }
};
}
这是协商功能
[Function("Negotiate")]
public SignalRConnectionInfo Negotiate(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "v1/negotiate")]
HttpRequestData req,
[SignalRConnectionInfoInput(HubName = "myhub")]
SignalRConnectionInfo connectionInfo)
{
return connectionInfo;
}
我尝试搜索更多信息,但找不到有用的信息。 我希望我能够控制服务器的响应,并能够以其他形式通知我的订阅者。
要从隔离的 Azure Functions 返回
HttpResponseData
而不是 SignalRMessageAction
,同时仍通过 SignalR 通知订阅者,您可以按照以下步骤操作:
单独的 SignalR 调用和 HTTP 响应:
SignalRMessageAction
。处理 SignalR 调用:
返回HttpResponseData:
下面的示例代码使用 HttpResponseData。
代码:
[Function("index")]
public HttpResponseData GetWebPage([HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequestData req)
{
var response = req.CreateResponse(HttpStatusCode.OK);
response.WriteString(File.ReadAllText("content/index.html"));
response.Headers.Add("Content-Type", "text/html");
return response;
}
[Function("negotiate")]
public async Task<HttpResponseData> Negotiate([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
{
_logger.LogInformation("C# HTTP trigger function processed a request.");
var negotiateResponse = await MessageHubContext.NegotiateAsync(new() { UserId = req.Headers.GetValues("userId").FirstOrDefault() });
var response = req.CreateResponse();
// We need to make sure the response JSON naming is camelCase, otherwise SignalR client can't recognize it.
await response.WriteAsJsonAsync(negotiateResponse, JsonObjectSerializer);
return response;
}