我使用VS2012创建了一个WCF网站(添加->新网站->WCF服务)。我想让网站返回 JSON 格式的数据。
我编辑了 Service.cs 和 IService.cs 类,并将 web.config 编辑为如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet(UriTemplate = "one", ResponseFormat = WebMessageFormat.Json)]
string One();
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "two", ResponseFormat = WebMessageFormat.Json)]
string Two();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
public class Service : IService
{
public string One()
{
return "{\"Result\":\"One\"}";
}
public string Two()
{
return "{\"Result\":\"Two\"}";
}
}
<?xml version="1.0"?>
<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 name="ZuantResearchWCFServiceWebSite.Service" behaviorConfiguration="ServiceBehaviour">
<endpoint address="" behaviorConfiguration="restfulBehaviour" bindingConfiguration="" binding="webHttpBinding" contract="ZuantResearchWCFServiceWebSite.IService" ></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- 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>
<endpointBehaviors>
<behavior name="restfulBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
</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>
Service.svc 文件包含一行:
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>
转到浏览器,然后点击以下任一 URI:
http://localhost:54795/Service.svc/one
http://localhost:54795/Service.svc/two
在每种情况下,我都会得到一个完全空白的页面。
为什么我的网站没有返回任何 JSON?
我创建了一个具有完全相同的服务和配置等的 WCF 服务应用程序,这确实将 JSON 正确返回到浏览器。
谁能解释配置 WCF 服务网站和 WCF 服务应用程序之间的主要区别,并告诉我为什么应用程序返回 JSON 而网站没有?
非常感谢。