【问题标题】:Define WCF Service to Get JSON Data定义 WCF 服务以获取 JSON 数据
【发布时间】:2019-12-10 08:18:50
【问题描述】:

我希望我的 WCF 服务返回 json。

我正在使用 Visual Studio 2013 (VB.NET/ASP.NET 4.6.1)

在我的 aspx 页面(位于名为 DataUnit 的文件夹中)中,我尝试调用位于(目前)在 aspx 页面的同一文件夹中的 WCF 服务。

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: 'Service.svc/GetCustomers',
        data: '{"MyDate": "' + dateval + '"}',......

但我收到错误 404

如果我在浏览器中可视化 Service.svc (http://localhost:64367/DataUnit/Service.svc) 我会收到消息

服务创建

测试服务.....

svcutil.exe http://localhost:64367/DataUnit/Service.svc?wsdl

我也已在面板控制中激活 Windows Communication Foundation HTTP 激活 Windows Communication Foundation 非 HTTP 激活

我花了一整天的时间来解决,但我快疯了。

这是我的代码

web.config

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service name="MyNameSpace.Service" behaviorConfiguration="ServiceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="MyNameSpace.Service" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
      </service>
    </services>
  </system.serviceModel>

服务.svc

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
Imports Newtonsoft.Json

<ServiceContract()>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class Service
    <OperationContract()>
    <System.ServiceModel.Web.WebInvoke(Method:="POST", _
            ResponseFormat:=System.ServiceModel.Web.WebMessageFormat.Json)> _
    Public Function GetCustomers(ByVal MyDate As String) As String
        Try
            Dim gd As New GetOracleData
            Dim b As String = Chr(34)
            Dim newdataset As DataSet
            Dim RAPPID As String = "01"

            newdataset = gd.GetMyData(MyDate , RAPPID)
            Dim json2 As String = JsonConvert.SerializeObject(newdataset, Newtonsoft.Json.Formatting.Indented)

            Return json2
        Catch ex As Exception
        End Try
    End Function
End Class

SVC 标记:

<%@ ServiceHost Language="VB" Debug="true" Service="MyNameSpace.Service" CodeBehind="Service.svc.vb" %>

RouteConfig.vb

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
Imports System.Web.Routing

Public Module RouteConfig
    Public Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

        routes.MapRoute(
            name := "Default",
            url := "{controller}/{action}/{id}",
            defaults := New With {.action = "Index", .id = UrlParameter.Optional}
        )
    End Sub
End Module

更新

我相信问题出在这个问题上,但我不知道为什么以及如何必须为简单的 ASPX 页面实现控制器。

[HttpException]: The controller for path &#39;/DataUnit/Service.svc/GetCustomers&#39; was not found or does not implement IController.
   in System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
   in System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
   in System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   in System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   in System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
   in System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
   in System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   in System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   in System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

【问题讨论】:

    标签: asp.net wcf


    【解决方案1】:

    兄弟, 我们需要将 WebHttp 端点行为添加到服务端点。如下所示。

      <system.serviceModel>
        <behaviors>
          <endpointBehaviors>
            <behavior name="WebApplication1.CostServiceAspNetAjaxBehavior">
              <enableWebScript/>
              <webHttp />
            </behavior>
          </endpointBehaviors>
          <serviceBehaviors>
            <behavior>
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
        <services>
          <service name="WebApplication1.CostService">
            <endpoint address="" behaviorConfiguration="WebApplication1.CostServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="WebApplication1.CostService"/>
          </service>
        </services>
      </system.serviceModel>
    

    详情
    https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/webhttp
    如果问题仍然存在,请随时告诉我。

    【讨论】:

    • 感谢兄弟,添加了 但结果相同,错误 404。
    • Http 404错误主要表示找不到文件。请注意服务地址。为了测试,你可以在浏览器地址栏中输入服务地址,通过使用[WebGet]装饰方法来访问服务
    • 请在ajax请求中使用绝对服务地址。如下所示。 “~/DataUnit/Service.svc/GetCustomers”。
    • 如果我使用“~/DataUnit/Service.svc/GetCustomers”总是错误 404 但使用 Firefox 检查器我可以看到请求的 URL 是 localhost:64367/DataUnit/~/DataUnit/Service.svc/GetCustomers。很奇怪。
    • 尝试用实际路径替换地址。如果我们使用正确的地址,我们可以看到请求信息和响应错误吗?
    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    相关资源
    最近更新 更多