Restful网络服务端点未找到。

6
我正在尝试构建一个基本的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();
        }
    }
}

Global.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>

2
我不确定那是否导致了异常,但是你的 CurrentTime 方法上缺少了 [OperationContract] 属性。 - Conrad Frix
自从.NET 4.0版本以后,如果你在WCF HTTP服务中使用[WebGet]或[WebInvoke],就不再需要[OperationContract]了。 - carlosfigueira
全局.asax文件位于哪个虚拟目录/应用程序中?如果它不直接位于IIS根目录下,则地址应为http://localhost:PORT/ApplicationName/TimeService/CurrentTime。 - carlosfigueira
@carlosfigueira 我只是通过 Visual Studio 进行调试来运行它。当它加载浏览器时,您可以通过 http://localhost:PORT 访问它,这将显示解决方案的所有文件。 - atrljoe
尝试更改为匿名端口。 - Gregory Nozik
1个回答

4

1
如果您能发布那个,那将非常有帮助。 - atrljoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接