如何在浏览器中调用WCF REST服务方法

时间:2017-06-10 16:13:19

标签: json rest wcf wcf-endpoint webhttpbinding

我创建了返回JSON格式的WCF REST服务。 我的问题是"我无法在浏览器中找到我的操作合同方法?" enter image description here

以下是我的服务合同

using System.ServiceModel;
using System.ServiceModel.Web;
namespace WcfService1
{

    [ServiceContract]
    public interface IService1
    {

            [OperationContract]
            WcfService1.Service1.Person GetData(string id);

    }


}

Service1.svc.cs

using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{

    public class Service1 : IService1
    {
      [WebInvoke(Method = "GET",
                    ResponseFormat = WebMessageFormat.Json,
                    UriTemplate = "data/{id}")]
        public Person GetData(string id)
        {
            // lookup person with the requested id 
            return new Person()
            {
                Id = Convert.ToInt32(id),
                Name = "Leo Messi"
            };
        }


        public class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }
}

以下是EndPoint

<system.serviceModel>
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="http://localhost:62030/Service1.svc" binding="webHttpBinding" contract="WcfService1.IService1"/>
      </service>
    </services>
    <client>
      <endpoint name="JsonService1" address="http://localhost:62030/Service1.svc" binding="webHttpBinding" contract="WcfService1.IService1"></endpoint>
    </client>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="webHttpBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
  </system.serviceModel>

2 个答案:

答案 0 :(得分:0)

我通过在service1.cs

中添加以下Fsactory来解决
Factory="System.ServiceModel.Activation.WebServiceHostFactory"

Service1.cs

<%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

Json输出:enter image description here

答案 1 :(得分:0)

使用localhost:62030 / Service1.svc / data / 3。您使用的是错误的URI。调用的格式是服务名称,在你的情况下使用uritemplate url是localhost:62030 / Service1.svc而uritemplate是data / id所以cpmplete url是localhost:62030 / Service1.svc / data / 3