【发布时间】:2017-02-01 00:50:02
【问题描述】:
我在 .NET 中将 Web 应用程序开发为两个独立的应用程序,后端使用 webapi c#,用户界面使用 AngularJS。我只想在这个项目中添加聊天选项。我已经安装了 SignalR 并在 webapi 中添加了 ChatHub.cs 类。
在 WebAPI 中有一个名为 Startup.cs 的类
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
WebApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
app.UseWebApi(config);
app.MapSignalR();//added after installation of SignalR package
}
}
ChatHub 类
public class ChatHub : Hub
{
public static string emailIDLoaded = "";
public void Connect(string userName, string email)
{
emailIDLoaded = email;
var id = Context.ConnectionId;
using (SmartCampEntities dc = new SmartCampEntities())
{
var userdetails = new ChatUserDetail
{
ConnectionId = id,
UserName = userName,
EmailID = email
};
dc.ChatUserDetails.Add(userdetails);
dc.SaveChanges();
}
}
}
无论我从用户界面发送什么请求,它都会到达 webAPI 中的相应控制器。例如
$http({
method: 'GET',
url: $scope.appPath + "DashboardNew/staffSummary" //[RoutePrefix]/[Route]
}).success(function (result, status) {
data = result;
});
我的用户界面是一个单独的应用程序。如何从 UI 连接 signalR。 我尝试了一些东西,但没有成功。谁能建议我如何让它工作
html代码
<div>
<a class="btn btn-blue" ng-click="sendTask()">SendTask</a>
javascript
angular.module('WebUI').controller('DashboardCtrl', function ($scope, $window, $http, $modal, ngTableParams) {
$scope.header = "Chat";
$scope.sendTask = function () {
$http({
method: 'POST',
url: $scope.appPath + hubConnetion.server.sendTask("userName","email"),
})
}
});
【问题讨论】:
-
这与从网页定期使用 SignalR 没有什么不同。该文档很好,并且有很多关于如何使用它的示例。
-
你能分享任何例子或链接吗
-
不清楚您真正需要什么,或者更好的是,您需要帮助解决哪些故障。您想知道如何在 Angular 中集成 Signalr 启动,或者您遇到了失败,例如 CORS?
-
我想知道如何将 SignalR 集成到现有项目中。因为 Startup.cs 已经存在,所以我不知道我应该做哪些改变
标签: javascript c# asp.net angularjs asp.net-web-api