Wcf Rest Service GET 方法无法显示 JSON 数据

Posted

技术标签:

【中文标题】Wcf Rest Service GET 方法无法显示 JSON 数据【英文标题】:Wcf Rest Service GET Method Unable to display JSON data 【发布时间】:2018-05-19 20:38:49 【问题描述】:

我创建了 wcf Rest Service 来接受 POST 、 GET 和 DELETE 操作。当向服务器发出 GET 请求时,它不显示 JSON 数据并在 Google chrome 中显示 [] 符号。

这是界面。

[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetCustomers/prefix")]
string GetCustomers(string prefix);

这是实现。

public string GetCustomers(string prefix)


    List<object> customers = new List<object>();
    string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Holder_Last_Name LIKE @prefix + '%'";
    using (SqlConnection conn = new SqlConnection())
    
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        
            cmd.Parameters.AddWithValue("@prefix", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            
                while (sdr.Read())
                
                    customers.Add(new
                    
                        Tittle = sdr["Tittle"],
                        Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                        Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                        Account_Holder_DOB = sdr["Account_Holder_DOB"],
                        Account_Holder_House_No = sdr["Account_Holder_House_No"],
                        Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                        Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],    
                        Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                        Account_Number = sdr["Account_Number"] 
                     );
                 
             
             conn.Close();
             
         return (new javascriptSerializer().Serialize(customers));
     

这是 .SVC 文件。

<%@ ServiceHost Language="C#" Debug="true" Service="HalifaxWCFProject.HalifaxService"%>

这是 web.config 文件。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=;Initial Catalog=HalifaxDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="HalifaxDatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=;initial catalog=HalifaxDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.serviceModel>
    <services>
      <service name="HalifaxWCFProject.HalifaxService" behaviorConfiguration="mexBehaviour">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="REST" contract="HalifaxWCFProject.IHalifaxService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="REST">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

这是屏幕截图。

【问题讨论】:

你在执行请求时检查数据是否存在。 是的,我在数据库中有一些记录 【参考方案1】:

我是这样做的。您还确定这部分 RequestFormat = WebMessageFormat.Json 吗?

[OperationContract]
[WebInvoke(Method = "GET", 
           ResponseFormat = WebMessageFormat.Json, 
           BodyStyle = WebMessageBodyStyle.Wrapped, 
           UriTemplate = "register?serverCode=serverCode")]
string Registration(string strVal);
public string Registration(string strVal)

    return "";

希望这会有所帮助。

【讨论】:

是的。我还有其他方法可以返回记录列表,并且效果很好

以上是关于Wcf Rest Service GET 方法无法显示 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

尝试 GET 时出现 WCF REST 404

WCF REST 服务返回 405:jQuery AJAX GET 不允许的方法

传递流时出现 Wcf Rest Service 错误

验证WCF Rest Service中Json对象的结构

web service, wcf, wcf rest, web api之间的区别

WCF Web API WCF REST 和 Web Service 的区别