首页 > 解决方案 > 如何使用 WCF 服务?

问题描述

当我创建一个新的 WCF 服务时,我可以创建一个像这样的新方法:

 [OperationContract]
 [WebInvoke(Method = "GET", UriTemplate = "TryThis", ResponseFormat = WebMessageFormat.Json)]
 string TryThis();

返回简单字符串的函数。

我可以将它与测试客户端 WCF 一起使用,并且可以正常工作。但是当我想通过 Chrome、邮递员或我的 Android 应用程序访问我的服务时,我不能。

我尝试使用这些网址:

 http://localhost:54792/Service1.svc/TryThis
 http://tempuri.org/IService1/TryThis

当我使用“ http://localhost:54792/Service1.svc ”时,我有主页,所以没关系。但是我无权访问我的服务的任何方法。

错误是 400 错误。但我没有任何消息表明此错误在哪里。我不知道这是否是我的 IIS 服务器的配置,如果这是我的服务。我完全被封锁了。

这是我的web.config

<?xml version="1.0" encoding="utf-8"?>
 <configuration>
   <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
   </appSettings>
    <system.web>
     <compilation debug="true" targetFramework="4.7.1" />
     <httpRuntime targetFramework="4.7.1"/>
    </system.web>
    <system.serviceModel>
     <behaviors>
       <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <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"/>
     <directoryBrowse enabled="true"/>
   </system.webServer>
 </configuration>

PS:我已经看过这篇文章:“如何使用 Web 引用访问 WCF 服务? ”但这对我没有帮助。

标签: wcf

解决方案


看来你是在IIS里托管WCF服务,想发布一个Restful风格的服务,可以参考下面的代码。
服务器:IService.cs

namespace WcfService5
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        string GetData(int value);
    }
}

服务器:Service.svc.cs

namespace WcfService5
{
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    }
}

网络配置。

<system.serviceModel>
    <services>
      <service name="WcfService5.Service1">
        <endpoint address="" binding="webHttpBinding" contract="WcfService5.IService1" behaviorConfiguration="MyRest"></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="MyRest">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

结果。 在此处输入图像描述

如果有什么我可以帮忙的,请随时告诉我。


推荐阅读