使用 ASP.NET 在 Azure 上一起托管 WCF REST 和 NET.TCP 端点
我通过 Windows Azure 上的 ASP.NET 应用程序托管我的 REST 服务。它运行完美,但几天前我需要一个角色间通信服务,我构建了我的服务,但在托管它时遇到了问题。
Global.asax 中的这段代码在我的本地 Azure 开发服务器中运行良好,但在 Azure 云中不起作用。
正确托管它们的最佳方法是什么?
Global.asax:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
StartNotificationServiceHost();
RegisterRoutes();
}
public ServiceHost ServiceHost { get; private set; }
private void RegisterRoutes()
{
var hostfactory = new WebServiceHostFactory();
RouteTable.Routes.Add(new ServiceRoute("REST/Companies",hostfactory, typeof(Companies)));
RouteTable.Routes.Add(new ServiceRoute("REST/Public", hostfactory, typeof(Public)));
RouteTable.Routes.Add(new ServiceRoute("REST/Users", hostfactory, typeof(Users)));
RouteTable.Routes.Add(new ServiceRoute("REST/Contacts", hostfactory, typeof(Contacts)));
RouteTable.Routes.Add(new ServiceRoute("REST/Projects", hostfactory, typeof(Projects)));
RouteTable.Routes.Add(new ServiceRoute("REST/Instances", hostfactory, typeof(Instances)));
RouteTable.Routes.Add(new ServiceRoute("REST/Activity", hostfactory, typeof(Activity)));
RouteTable.Routes.Add(new ServiceRoute("REST/Search", hostfactory, typeof(Search)));
RouteTable.Routes.Add(new ServiceRoute("REST/Tasks", hostfactory, typeof(Tasks)));
RouteTable.Routes.Add(new ServiceRoute("REST/Documents", hostfactory, typeof(Documents)));
}
private void StartNotificationServiceHost()
{
Trace.WriteLine("Starting Service Host", "Information");
NotificationServiceHost serviceHostBase = new NotificationServiceHost();
serviceHostBase.RecycleNotificationRecieved += new RecycleNotificationRecievedEventHandler(ServiceHost_RecycleNotificationRecieved);
serviceHostBase.CheckInstanceStatusRecieved += new CheckInstanceStatusRecievedEventHandler(serviceHostBase_CheckInstanceStatusRecieved);
ServiceHost = new ServiceHost(serviceHostBase);
this.ServiceHost.Faulted += (sender, e) =>
{
Trace.TraceError("Service Host fault occured");
this.ServiceHost.Abort();
Thread.Sleep(500);
this.StartNotificationServiceHost();
};
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
RoleInstanceEndpoint notificationServiceHostEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["NotificationServiceEndPoint"];
this.ServiceHost.AddServiceEndpoint(
typeof(INotifyService),
binding,
String.Format("net.tcp://{0}/NotifyService", notificationServiceHostEndPoint.IPEndpoint)
);
try
{
this.ServiceHost.Open();
Trace.TraceInformation("Service Host Opened");
}
catch (TimeoutException timeoutException)
{
Trace.TraceError("Service Host open failure, Time Out: " + timeoutException.Message);
}
catch (CommunicationException communicationException)
{
Trace.TraceError("Service Host open failure, Communication Error: " + communicationException.Message);
}
Trace.WriteLine("Service Host Started", "Information");
}
InstanceItem serviceHostBase_CheckInstanceStatusRecieved(object sender, int e)
{
...
}
void ServiceHost_RecycleNotificationRecieved(object sender, NotificationMessage e)
{
...
}
}
Web.config/ServiceModel 部分:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- This behavior enables API Key Verification -->
<serviceAuthorization serviceAuthorizationManagerType="OfisimCRM.Webservice.APIKeyAuthorization, OfisimCRM.Webservice" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp />
<serviceValidator />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="serviceValidator" type="OfisimCRM.Webservice.WebHttpWithValidationBehaviorExtension, OfisimCRM.Webservice, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint crossDomainScriptAccessEnabled="true" faultExceptionEnabled="true" hostNameComparisonMode="WeakWildcard" name="" defaultOutgoingResponseFormat="Json" helpEnabled="true" automaticFormatSelectionEnabled="true" maxBufferSize="65536" maxReceivedMessageSize="104857600" transferMode="Streamed" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
ServiceDefinition/WebRole:
<WebRole name="OfisimCRM.WebClient" vmsize="Small">
<Sites>
<Site name="Web">
<Bindings>
<Binding name="Endpoint1" endpointName="Endpoint1" />
</Bindings>
</Site>
</Sites>
<Endpoints>
<InputEndpoint name="Endpoint1" protocol="http" port="80" />
<InternalEndpoint name="NotificationServiceEndPoint" protocol="tcp" />
</Endpoints>
<Imports>
<Import moduleName="Diagnostics" />
<Import moduleName="RemoteAccess" />
</Imports>
<ConfigurationSettings>
</ConfigurationSettings>
</WebRole>
错误:
The server encountered an error processing the request. The exception message is 'Could not connect to net.tcp://x.x.x.29:8000/NotifyService. The connection attempt lasted for a time span of 00:00:21.0918600. TCP error code 10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond x.x.x.29:8000. '. See server logs for more details.
I'm hosting my REST services by an ASP.NET application on Windows Azure. It's working perfect, but I needed an Inter-Role communication service a few days ago, I built my service but I have problems with hosting it.
This Code in my Global.asax works great in my local Azure Development Server but It did not work in Azure Cloud.
What is the best way to host them correctly?
Global.asax:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
StartNotificationServiceHost();
RegisterRoutes();
}
public ServiceHost ServiceHost { get; private set; }
private void RegisterRoutes()
{
var hostfactory = new WebServiceHostFactory();
RouteTable.Routes.Add(new ServiceRoute("REST/Companies",hostfactory, typeof(Companies)));
RouteTable.Routes.Add(new ServiceRoute("REST/Public", hostfactory, typeof(Public)));
RouteTable.Routes.Add(new ServiceRoute("REST/Users", hostfactory, typeof(Users)));
RouteTable.Routes.Add(new ServiceRoute("REST/Contacts", hostfactory, typeof(Contacts)));
RouteTable.Routes.Add(new ServiceRoute("REST/Projects", hostfactory, typeof(Projects)));
RouteTable.Routes.Add(new ServiceRoute("REST/Instances", hostfactory, typeof(Instances)));
RouteTable.Routes.Add(new ServiceRoute("REST/Activity", hostfactory, typeof(Activity)));
RouteTable.Routes.Add(new ServiceRoute("REST/Search", hostfactory, typeof(Search)));
RouteTable.Routes.Add(new ServiceRoute("REST/Tasks", hostfactory, typeof(Tasks)));
RouteTable.Routes.Add(new ServiceRoute("REST/Documents", hostfactory, typeof(Documents)));
}
private void StartNotificationServiceHost()
{
Trace.WriteLine("Starting Service Host", "Information");
NotificationServiceHost serviceHostBase = new NotificationServiceHost();
serviceHostBase.RecycleNotificationRecieved += new RecycleNotificationRecievedEventHandler(ServiceHost_RecycleNotificationRecieved);
serviceHostBase.CheckInstanceStatusRecieved += new CheckInstanceStatusRecievedEventHandler(serviceHostBase_CheckInstanceStatusRecieved);
ServiceHost = new ServiceHost(serviceHostBase);
this.ServiceHost.Faulted += (sender, e) =>
{
Trace.TraceError("Service Host fault occured");
this.ServiceHost.Abort();
Thread.Sleep(500);
this.StartNotificationServiceHost();
};
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
RoleInstanceEndpoint notificationServiceHostEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["NotificationServiceEndPoint"];
this.ServiceHost.AddServiceEndpoint(
typeof(INotifyService),
binding,
String.Format("net.tcp://{0}/NotifyService", notificationServiceHostEndPoint.IPEndpoint)
);
try
{
this.ServiceHost.Open();
Trace.TraceInformation("Service Host Opened");
}
catch (TimeoutException timeoutException)
{
Trace.TraceError("Service Host open failure, Time Out: " + timeoutException.Message);
}
catch (CommunicationException communicationException)
{
Trace.TraceError("Service Host open failure, Communication Error: " + communicationException.Message);
}
Trace.WriteLine("Service Host Started", "Information");
}
InstanceItem serviceHostBase_CheckInstanceStatusRecieved(object sender, int e)
{
...
}
void ServiceHost_RecycleNotificationRecieved(object sender, NotificationMessage e)
{
...
}
}
Web.config/ServiceModel section:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- This behavior enables API Key Verification -->
<serviceAuthorization serviceAuthorizationManagerType="OfisimCRM.Webservice.APIKeyAuthorization, OfisimCRM.Webservice" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp />
<serviceValidator />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="serviceValidator" type="OfisimCRM.Webservice.WebHttpWithValidationBehaviorExtension, OfisimCRM.Webservice, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint crossDomainScriptAccessEnabled="true" faultExceptionEnabled="true" hostNameComparisonMode="WeakWildcard" name="" defaultOutgoingResponseFormat="Json" helpEnabled="true" automaticFormatSelectionEnabled="true" maxBufferSize="65536" maxReceivedMessageSize="104857600" transferMode="Streamed" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
ServiceDefinition/WebRole:
<WebRole name="OfisimCRM.WebClient" vmsize="Small">
<Sites>
<Site name="Web">
<Bindings>
<Binding name="Endpoint1" endpointName="Endpoint1" />
</Bindings>
</Site>
</Sites>
<Endpoints>
<InputEndpoint name="Endpoint1" protocol="http" port="80" />
<InternalEndpoint name="NotificationServiceEndPoint" protocol="tcp" />
</Endpoints>
<Imports>
<Import moduleName="Diagnostics" />
<Import moduleName="RemoteAccess" />
</Imports>
<ConfigurationSettings>
</ConfigurationSettings>
</WebRole>
Error:
The server encountered an error processing the request. The exception message is 'Could not connect to net.tcp://x.x.x.29:8000/NotifyService. The connection attempt lasted for a time span of 00:00:21.0918600. TCP error code 10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond x.x.x.29:8000. '. See server logs for more details.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
角色实例访问已受到防火墙限制。通常,实例仅接受来自负载均衡器的连接。如下所示,将设置添加到服务定义文件(*.csdef)中,并且需要接受连接。
或者,您可以在启动任务中使用 netsh 命令明确添加连接规则。
前任)
netsh advfirewall 防火墙添加规则名称 =“YourEndPoint”dir = in action =allow localport = 80 协议 = tcp
====
“InternalEndpoint”是动态端口吗?如果可能的话,您能否在.csdef和启动任务中设置固定端口。
ex)
和
====
或者,环境变量可用如下:
并且您在启动任务中使用环境变量
Role instances access has been restricted by the Firewall. Usually, the instance accepts connections only from the load balancer. You add setting to service definition file (*.csdef) as follows, and it is necessary to accept connection.
Alternatively, you can add rule the connection expresily using netsh command in Startup Task.
ex)
netsh advfirewall firewall add rule name="YourEndPoint" dir=in action=allow localport=80 protocol=tcp
====
Is 'InternalEndpoint' a dynamic port? If possible, Could you set a fixed port in .csdef and startup task.
ex)
and
====
Or, Environment Variable is available as follows:
and You use environment variable in startup tasks