【发布时间】:2011-11-30 19:35:28
【问题描述】:
我正在尝试构建一个基本的 REST Web 服务,它只返回当前时间,每当我尝试调用我的服务http://localhost:PORT/TimeService/CurrentTime 时,都会收到以下错误:
未找到端点。请参阅服务帮助页面进行构建 对服务的有效请求。
我做错了什么?您可以在下面找到我正在使用的所有代码。谢谢你
Service1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace WcfRestService1
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class TimeService
{
[WebGet(UriTemplate = "CurrentTime")]
public string CurrentTime()
{
return DateTime.Now.ToString();
}
}
}
全球.asax
using System;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Routing;
namespace WcfRestService1
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private static void RegisterRoutes()
{
RouteTable.Routes.Add(new ServiceRoute("TimeService",
new WebServiceHostFactory(), typeof(TimeService)));
}
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
【问题讨论】:
-
我不知道这是否会导致执行,但您不会错过 CurrentTime 方法上的
[OperationContract]属性 -
从 .NET 4.0 开始,如果您有用于 WCF HTTP 服务的 [WebGet] 或 [WebInvoke],则不再需要 [OperationContract]。
-
global.asax 位于哪个 vdir/application 中?如果不是直接在 IIS 根目录,那么地址应该是localhost:PORT/ApplicationName/TimeService/CurrentTime
-
@carlosfigueira 我只是通过 Visual Studio 调试它来运行它。当它加载浏览器时,您可以通过localhost:PORT 访问它,这只会显示解决方案的所有文件。
-
尝试改成匿名端口。