我有一个Windows服务的工作实现,充当SignalR客户端,向ASP.NET MVC(服务器)中的集线器上的方法发送消息。我只需要知道如何使用MVC在视图中显示我收到的字符串。
我在Windows服务中设置了以下客户端代码,设置了hubConnection并调用了“Hello”方法:
protected override async void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
try
{
var hubConnection = new HubConnection("http://localhost/AlphaFrontEndService/signalr", useDefaultUrl: false);
IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");
await hubConnection.Start();
// Invoke method on hub
await alphaProxy.Invoke("Hello", "Message from Service");
}
catch (Exception ex)
{
eventLog1.WriteEntry(ex.Message);
}
}
当我启动服务时,它会使用此中心和方法调用我的MVC应用程序:
public class AlphaHub : Hub
{
public void Hello(string message)
{
// We got the string from the Windows Service
// using SignalR. Now need to send to the clients
Clients.All.addNewMesssageToPage(message);
}
}
我在HomeController上设置了一个方法:
public ActionResult Messaging()
{
return View();
}
然后是Messaging视图:
@{
ViewBag.Title = "Messaging";
}
<h2>Messaging</h2>
<ul id="messages"></ul>
@section scripts
{
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function() {
var alpha = $.connection.alphaHub;
// Create a function that the hub can call back to display messages
alpha.client.addNewMessageToPage = function (message) {
// Add the message to the page.
$('<li />').text(message).appendTo('#messages');
};
$.connection.hub.start();
});
</script>
}
它没有更新/ Home / Messaging中的浏览器
答案 0 :(得分:1)
在SignalR网站上有一些非常好的例子比任何人都可以在这里发布的答案要好...... http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20-and-mvc-5
但简而言之(几乎从上面的教程中逐字逐句......
在你的Razor视图中:
@{
ViewBag.Title = "Chat";
}
<ul id="messages"><ul>
@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. (make sure the version matches your local copy) -->
<script src="~/Scripts/jquery.signalR-2.0.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var alpha = $.connection.alphaHub;
// Create a function that the hub can call back to display messages.
alpha.client.addNewMessageToPage = function (message) {
// Add the message to the page.
$('<li />').text(message).appendTo('#messages');
};
$.connection.hub.start();
});
</script>
}
在您的中心:
public class AlphaHub : Hub
{
public void Hello(string message)
{
Clients.All.addNewMessageToPage(message);
}
}