60秒创建JSON WCF RESTful服务

1、先配置App.Config文件:

 <?xml version="1.0"?>

<configuration>
  <system.serviceModel>
<services>
 <service name="WcfJsonRestService.Service1">
<endpoint address="http://localhost:8732/service1" 
 binding="webHttpBinding" 
 contract="WcfJsonRestService.IService1"/>
 </service>
</services>
<behaviors>
 <endpointBehaviors>
<behavior>
 <webHttp />
</behavior>
 </endpointBehaviors>
</behaviors>
  </system.serviceModel>
  <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

2、接口定义:

 using System.ServiceModel;

namespace WcfJsonRestService
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        Person GetData(string id);
    }
}
 3、接口实现:

using System;
using System.ServiceModel.Web;

namespace WcfJsonRestService
{
    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; }
    }
}

 4、调试--启用实例,并通过浏览器访问http://localhost:8732/service1/data/10 即可看到运行效果!

原文地址:https://www.cnblogs.com/liyanggzy/p/1985529.html