【发布时间】:2017-04-01 11:35:16
【问题描述】:
我创建了一个简单的 WCF 服务应用程序,并尝试更改 WCF 代码,使其也可以从客户端浏览器调用,但它只能从 WCF 客户端成功运行。
从浏览器运行,不调用 WCF 服务(但浏览器中没有错误消息)。
代码:
合同:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet]
string Test();
[OperationContract]
[WebGet]
string GetData(int value);
}
实施:
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public string Test()
{
return "test success";
}
}
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>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
项目网址:
http://localhost:1507/
浏览器 URL 行 - 测试方法:
http://localhost:1507/Service1.svc/Test
谢谢。
【问题讨论】:
-
“从浏览器运行”是什么意思?跑什么?
Test是一个操作,而不是 URL。你不能用 GET 来调用它。这不是 WCF 的限制,这正是(SOAP)Web 服务的工作方式。您是否将 Web 服务与 REST API 混淆了? -
因为 WCF 服务从 localhost 运行,所以我从本地浏览器运行“localhost:1507/Service1.svc/Test”行。
-
我将绑定更改为 binding="webHttpBinding",它将使用 REST API 运行。
-
如果您需要 REST API,请使用 Web API,而不是 WCF。在 ASP.NET MVC 和 Web API 发布之前,WCF REST API 被添加为权宜之计。甚至不推荐使用 JSON 序列化程序 (JavascriptSerializer)。 ASP.NET Web API 使用 Json.NET
-
我现在才WCF,明天要面试,我需要创建一个服务器端。有办法改变 WCF,让它能够从浏览器运行吗?