WCF UriTemplate to match base address

159 Views Asked by At

How I can call an endpoint with the URL address exactly the same as the base address?

        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);

This is the Service and I want to call it with http://localhost:1387

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

There are 2 best solutions below

0
On

In WCF, if you do not set UriTemplate, WCF will add the method name after the base address as the URI of the service call. This is the interface for my service:

    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);
}

This is the help document after the service is started,you can see that even if I don't set UriTemplate, WCF still uses the method name as UriTemplate.So the base address cannot be the same as the address of the calling service. enter image description here

0
On

According to your question description, I did a demo, this is the interface:

[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);
}

This is my base address:

enter image description here

Through the help document, you can see the URI is still different from the base address.

enter image description here

Here's some information about the UriTemplate, wish it will be useful for you:

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