[C#.NET][WCF] 使用 WCF Service Application 實作 RESTful 服務,並回傳 JSON
- 必需要定義 WebGet 或 WebInvoke
- UriTemplate 屬性
- RequestFormat / ResponseFormat 屬性
- 必需要是 webHttpBinding
實作步驟:
public class User
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
服務合約類別,加上 WebGet 或 WebInvoke 特性
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "user",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
User GetUser();
[OperationContract]
[WebInvoke(UriTemplate = "users",
Method = "GET",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
IEnumerable<User> GetUsers();
}
{ public User GetUser() { return new User() { Name = "yao", Age = 112 }; } public IEnumerable<User> GetUsers() { return new List<User>() { new User(){Name = "yao1",Age = 11}, new User(){Name = "yao2",Age = 21}, new User(){Name = "yao3",Age = 12}, new User(){Name = "yaoˋ",Age = 32}, }; } }
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="seviceBehavior0" name="WcfService2.Service1">
<endpoint address="" behaviorConfiguration="endpointBehavior0"
binding="webHttpBinding" bindingConfiguration="" contract="WcfService2.IService1" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="endpointBehavior0">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="seviceBehavior0">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
文章出自:http://www.dotblogs.com.tw/yc421206/archive/2013/10/11/123893.aspx
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET