配置WCF WebSite以支持从浏览器进行RESTful访问

时间:2013-07-25 17:43:26

标签: c# wcf web-services web-config soa

我使用VS2012创建了一个新的WCF网站(添加 - >新网站 - > WCF服务)。

'开箱即用',这给了我以下web.config文件:

<?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>
    <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="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>

它还为我提供了一个初始服务类,如下所示:

public class Service : IService
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

然后我按F5启动项目,它会启动一个列出目录内容的浏览器窗口,包括Service.svc。

我想输入一个URL来调用GetData方法。我在浏览器地址栏中键入了什么,以及如何配置和/或修饰服务,以便在浏览器中键入URL并查看返回的JSON格式字符串?

1 个答案:

答案 0 :(得分:1)

使用以下属性在合同(IService界面)中标记操作 - [WebInvoke(Method =“GET”,BodyStyle = WebMessageBodyStyle.WrappedRequest,ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json,UriTemplate =“GetData / { ID}”)] 然后尝试通过添加GetData / [任意数字]

从浏览器调用您的服务