我从MVC Controller动作中调用SignalR
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
var ret = context.Clients.Client("Whatever").getValue(userId);
Run Code Online (Sandbox Code Playgroud)
无论如何我可以从动作中的客户端调用getValue()方法获得响应吗?
我尝试了几种方法,但根本无法获得任何ret值.我很确定这不适用于SignalR Hub但无法找到有关此内容的文档.
我考虑过的一个解决方案是在收到getValue之后客户端会在Hub中调用一个方法但是我不得不破解我从Hub获取响应到控制器的方法.
小智 30
从JS调用SignalR服务并具有返回值很简单!(对不起,我没有很好地阅读原始问题,可能已经很晚了).你可以做得很好:
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://localhost:8080/SignalR";
// Declare a proxy to reference the hub.
var myHub = $.connection.myHub;
// Start the connection.
$.connection.hub.start().done(function () {
//Once connected, can call methods with return parameters:
myHub.server
.getValue("userId")
.done(function (result) {
$('#resultText').val(result); //display in textbox the return value of a call to public string GetValue(string userId)
});
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
适用于SignalR 2.0
Pet*_*ete 21
SignalR不像消息传递机制那样是RPC机制.因此,没有返回值的真实概念.
如果你想这样做,你就会破解它.您可以简单地做一些事情,在服务器中,您调用getValue()然后客户端的响应是使用返回值调用服务器.
所以,例如,在你的javascript中,你可以有类似的东西:
myHub.client.getValue = function(userId) {
var retVal;
... set your retVal here ...
myHub.returnValue(userId, retVal)
}
Run Code Online (Sandbox Code Playgroud)
然后让服务器实现returnValue()方法......
小智 6
在服务器上:
public bool TestBoolRetVal()
{
return true;
}
Run Code Online (Sandbox Code Playgroud)
在 C# 客户端上:
bool bres = HubProxy.Invoke< bool >("TestBoolRetVal").Result;
Run Code Online (Sandbox Code Playgroud)
当然,您可以定义任何签名。
在net6中,rpc是,示例:Server,
public class FnHub : Hub
{
public double Hypotenuse(double x, double y)
{
return Math.Sqrt(x * x + y * y);
}
}
Run Code Online (Sandbox Code Playgroud)
客户,
var _hubConnection = new HubConnectionBuilder()
.WithUrl(hubUrl)
.Build();
await _hubConnection.StartAsync();
var x = 7.0;
var y = 11.0;
var h = await _hubConnection.InvokeAsync<double>("Hypotenuse", x, y);
// h is 13,038404810405298
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26922 次 |
| 最近记录: |