0

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

2 回答 2

0

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

于 2020-05-15T07:54:55.023 回答
0

根据你的问题描述,我做了一个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);
}

这是我的基本地址:

在此处输入图像描述

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

在此处输入图像描述

以下是有关 UriTemplate 的一些信息,希望对您有用:

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

于 2020-06-11T07:03:12.097 回答