【发布时间】:2016-01-21 08:21:36
【问题描述】:
我想构建一个 Windows 服务,通过自托管 ASP.NET Web API 提供一些服务。另外,我想通过自托管 SignalR 通知客户一些更改。我认为 ASP.NET SignalR 将是通知中心的完美解决方案。
当我同时运行这两个服务时,它们不能一起工作。如果我删除 SignalR,自托管 API 将开始正常工作。反之亦然:删除 windows 服务,SignalR 可以正常工作。
我不确定我的问题是什么,是否可以同时为 asp.net Web API 和 SignalR 提供一个自托管的 Windows 服务?
我在相同和不同的端口上都试过了,但都不起作用。
还有一个问题,是否可以同时拥有两个端口?
我安装的包:
Microsoft.AspNet.WebApi.SelfHost
Microsoft.AspNet.SignalR.SelfHost
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.HttpListener
Microsoft.Owin.Hosting
Microsoft.Owin.Cors
我的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(WindowsService_HostAPI.Startup))]
namespace WindowsService_HostAPI
{
partial class SelfHostService : ServiceBase
{
IDisposable SignalR;
EventLog myLog = new EventLog();
private const string appId = "MYHUB";
public SelfHostService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
myLog.Source = "MY HUB ";
var config = new HttpSelfHostConfiguration("http://localhost:9090");
config.Routes.MapHttpRoute(
name: "API",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
HttpSelfHostServer server = new HttpSelfHostServer(config);
string CertLocation = "";
server.OpenAsync().Wait();
try
{
myLog.WriteEntry("Notification HUB Start " );
}
catch (Exception ex)
{
myLog.WriteEntry("Notification Failed TO Start : " + ex.Message + " |||| " + CertLocation);
}
// SignalR
string url = "http://localhost:9191";
SignalR = WebApp.Start(url);
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
try
{
push.StopAllServices(true);
SignalR.Dispose();
}
catch (Exception ex)
{
myLog.WriteEntry("Notification Failed TO Stop : " + ex.Message);
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class UserGroupNotification : Hub
{
public void Send(string UGID, string message)
{
Clients.All.addMessage(UGID, message);
}
}
}
【问题讨论】:
标签: c# asp.net api windows-services signalr