首页 > 解决方案 > 定义 WCF 服务以获取 JSON 数据

问题描述

我希望我的 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

我还在 Panel Control Windows Communication Foundation HTTP Activation Windows Communication Foundation Non-HTTP Activation 中激活了

我已经度过了一整天的时间来解决,但我快疯了。

这是我的代码

网络配置

<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" %>

路由配置.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.netwcf

解决方案


兄弟,我们需要将 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
如果问题仍然存在,请随时告诉我。


推荐阅读