首页 > 解决方案 > WCF UriTemplate 匹配基地址

问题描述

如何调用 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
    }

标签: wcfendpointuritemplatebase-address

解决方案


在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。所以基地址不能和调用服务的地址相同。 在此处输入图像描述


推荐阅读