【问题标题】:WCF UriTemplate to match base addressWCF UriTemplate 匹配基地址
【发布时间】:2020-05-13 13:39:42
【问题描述】:

如何调用 URL 地址与基地址完全相同的端点?

        string localhost = "http://localhost:1387";
        ServiceHost restHost = new ServiceHost(typeof(WebService), new Uri(localhost));
        restHost.AddServiceEndpoint(typeof(IWebService), new WebHttpBinding(), "").Behaviors.Add(new RestBehavior());
        hosts.Add(restHost);

这是服务,我想用http://localhost:1387 调用它

    [WebInvoke(Method = "GET", UriTemplate = "", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    public Stream GetBase()
    {
       //do action
    }

【问题讨论】:

    标签: wcf endpoint uritemplate base-address


    【解决方案1】:

    在WCF中,如果不设置UriTemplate,WCF会在基地址后面加上方法名作为服务调用的URI。 这是我的服务的接口:

        public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json)]
        Result GetUserData(string name);
        [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,BodyStyle =WebMessageBodyStyle.Wrapped)]
        Result PostUserData(UserData user);
        [OperationContract]
        [WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        Result PutUserData(UserData user);
        [OperationContract]
        [WebInvoke(Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        Result DeleteUserData(UserData user);
    }
    

    这是服务启动后的帮助文档,可以看到即使我不设置UriTemplate,WCF仍然使用方法名作为UriTemplate。所以基地址不能和调用的地址相同服务。

    【讨论】:

      【解决方案2】:

      根据你的问题描述,我做了一个demo,界面是这样的:

      [ServiceContract]
      public interface IUserService
      {        
          [WebInvoke(Method = "GET", UriTemplate = "", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
          IEnumerable<User> GetUser();
      
      
          [WebInvoke(Method = "POST", UriTemplate = "", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
          void Create(User user);
      }
      

      这是我的基本地址:

      enter image description here

      通过帮助文档可以看到URI还是和基地址不一样。

      enter image description here

      这里有一些关于 UriTemplate 的信息,希望对你有用:

      https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/uritemplate-and-uritemplatetable

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-11
        • 2013-04-16
        • 1970-01-01
        • 2013-09-14
        • 1970-01-01
        • 1970-01-01
        • 2013-11-23
        • 2015-03-30
        相关资源
        最近更新 更多