在ASP.NET MVC中动态更改WCF服务URL

时间:2017-06-04 07:11:31

标签: c# asp.net asp.net-mvc web-services wcf

我有一个解决方案,其中我有2个项目:

  1. ASP.NET MVC应用程序以使用wcf服务。
  2. 5 WCF服务。
  3. 我在项目中添加了一个Web服务引用1.现在,我需要根据用户使用不同的服务,例如。

    User Type 1:仅允许使用服务1。
    User Type 2:仅允许使用服务2。 等

    我有服务网址' ,如localhost:6227/Service1.svclocalhost:6227/Service2.svc等。

    我已将所有服务网址存储在 db 中,我需要更改每种用户类型的网址,以便仅使用其允许的服务而不添加更多端点,只更改来自后端基于用户类型。我需要相关的链接或代码来解决这个问题。

    修改

    Web配置中 我在mvc应用程序中添加了这个端点,我不想在这里使用web配置来更改地址,但是我希望在应用程序运行时更改每个用户类型的代码中的地址。

    <client>
          <endpoint address="http://localhost:6227/Service1.svc"
            binding="customBinding" bindingConfiguration="CustomBinding_IService1"
            contract="Service1.IService1" name="CustomBinding_IService1" />
        </client>
    

3 个答案:

答案 0 :(得分:3)

如果我完全意识到你的问题,你需要动态肥皂服务电话。也许是这样的:

private void CallService()
{
    var myBinding = new BasicHttpBinding();
    myBinding.Security.Mode = BasicHttpSecurityMode.None;
    var myEndpointAddress = new EndpointAddress("your url depend on user type");
    var client = new ClientService1(myBinding, myEndpointAddress);
    var outpiut = client.someCall();
    client.close();
}

答案 1 :(得分:0)

不确定我是否理解正确但您可以使用以下代码段(如果适合)。

//assuming you get string URL. Change type as per need.
string reqdURL = GetServiceURL(typeof(userObject));

private string GetServiceURL(Type userType)
{
    if (userType == typeof(UserType1))
    {
        // currently hardcoded but you can replace your own fetch logic
        return "localhost:6227/Service1.svc";
    }
    if (userType == typeof(UserType2))
    {
        return "localhost:6227/Service2.svc";
    }
    //and so on
}

答案 2 :(得分:0)

您可以这样做直接修改您的Endpoint地址:

ClientService1 ws = new ClientService1();
ws.Endpoint.Address = new EndpointAddress("Your new URL svc service");