我想构建一个Windows服务,通过自主ASP.NET Web API提供一些服务。另外,我想通过自主信号R告知客户一些变化。我认为ASP.NET SignalR将是通知集线器的完美解决方案。
当我运行这两项服务时,他们不能一起工作。如果我删除SignalR,Self-host 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);
}
}
}
答案 0 :(得分:2)
我在我的一个API上运行这样的配置--ApiControllers和Signalr hub在同一个URI上。我认为您的问题在于app.MapSignalR()piece。
以下是我在配置中的操作方法:
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
//I use attribute-based routing for ApiControllers
config.MapHttpAttributeRoutes();
appBuilder.Map("/signalr", map =>
{
var hubConfiguration = new HubConfiguration
{
};
map.RunSignalR(hubConfiguration);
});
config.EnsureInitialized(); //Nice to check for issues before first request
appBuilder.UseWebApi(config);
}