我在 VS 2013 中创建了一个新的 Empty Project,将其配置为使用 OwinHost 运行并按顺序安装以下包:
PM> Install-Package Owinhost
PM> Install-Package Microsoft.Owin
PM> Install-Package Microsoft.Owin.StaticFiles
PM> Install-Package Microsoft.AspNet.SignalR.JS
PM> Update-Package jQuery
PM> Install-Package Microsoft.AspNet.SignalR.Owin
然后,我添加了一个 Hub 类,如下所示:
using Microsoft.AspNet.SignalR;
namespace OwinHosting
{
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
在 startup.cs 我添加了这个:
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(OwinHosting.Startup))]
namespace OwinHosting
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HubConfiguration {EnableCrossDomain = true };
app.MapHubs(config);
app.UseStaticFiles("/Web");
}
}
}
最后,我添加了一个 Web 文件夹,将 Scripts 文件夹移到其中并添加了 index.html 页面:
<!DOCTYPE html>
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion"></ul>
</div>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-2.1.0.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.0.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="http://localhost:8888/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:8888/signalr";
// Declare a proxy to reference the hub.
var chat = $.connection.myHub;
// Create a function that the hub can call to broadcast messages.
chat.client.addMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
当我运行该页面时,它会询问“用户名”。当我输入一条消息并点击“发送”时,它只是没有任何回应。
我使用了 Chrome 工具,似乎“点击”事件中的“聊天”变量由于某种原因未定义。
任何想法?
谢谢