[英]Setting the endpoint in wcf service to be client specific. ASP.NET MVC
我正在創建一個ASP.net Web應用程序,該應用程序調用Web服務。 此Web服務(WCF)的端點配置取決於客戶端。 這意味着該終結點地址對於Web應用程序不同實例上的兩個不同用戶可能是不同的。 當前,我在Web.config中設置了地址,但是,這意味着當一個用戶設置端點時,也會為所有其他用戶設置該地址。
有沒有一種方法可以在客戶端設置端點,以使其不影響Web應用程序的其他實例?
我目前使用以下方法更改端點:
BasicHttpsBinding binding = new BasicHttpsBinding("ServiceSoap");
EndpointAddress epa = new EndpointAddress(new Uri(newUrl));
service = new ServiceSoapClient(binding, epa);
如您所說,由於配置文件已對服務端點地址進行了硬編碼,因此我們可以使用Channel Factory調用服務,這是在調用服務時需要在運行時指定服務端點地址和綁定信息的方式。
假設下面有一個服務器端服務。
服務器端(10.157.13.69)。
class Program
{
static void Main(string[] args)
{
using (ServiceHost sh = new ServiceHost(typeof(MyService)))
{
sh.Open();
Console.WriteLine("Service is ready....");
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
interface IService
{
[OperationContract]
string GetData();
}
public class MyService : IService
{
public string GetData()
{
return $"Hello, Now is {DateTime.Now.ToString()}";
}
}
App.config(服務器端)。
<system.serviceModel>
<services>
<service name="Server1.MyService">
<endpoint address="" binding="basicHttpBinding" contract="Server1.IService"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:5577"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
客戶端調用。
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://10.157.13.69:5577");
BasicHttpBinding binding = new BasicHttpBinding();
ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, new EndpointAddress(uri));
IService service = factory.CreateChannel();
try
{
var result = service.GetData();
Console.WriteLine(result);
}
catch (Exception)
{
throw;
}
}
}
[ServiceContract]
interface IService
{
[OperationContract]
string GetData();
}
在客戶端調用過程中,我們在運行時手動指定服務端點信息,然后調用服務。 我認為這可能是您要求的解決方案。
請參考以下文件。
https://docs.microsoft.com/zh-cn/dotnet/api/system.servicemodel.channelfactory-1?view=netframework-4.8
https://docs.microsoft.com/zh-cn/dotnet/framework/wcf/feature-details/how-to-use-the-channelfactory
https://www.c-sharpcorner.com/UploadFile/ff2f08/channel-factory-in-wcf/
請隨時告訴我是否有什么我可以幫助的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.