“对象引用未设置为对象的实例。”和connectionString

时间:2014-02-25 10:06:44

标签: c# jquery wcf

我有一个Web服务WCF,我想从Jquery中检索数据。

但成功在msg中返回null:

$.ajax({
 type: 'GET',
 url: 'http://localhost:52768/Service1/Statistic_1',
 contentType: 'application/json; charset=utf-8',
 dataType: 'json',
 success: function (msg) {
    response = msg.Items;
    console.log(msg);

    for (var i = 0; i < response.length; i++) {
        allstat1[i] = [response[i].Geografisch_zone];
    }
    fillDataTable(allstat1);
 },
  error: function (e) {
    alert("error loading statistic 1");
 }
 });
 }

我使用了调试,它在SqlConnection的Statistic_1方法中捕获了一个异常:

public static List<Statistic_1> Helper_Statistic_1()
    {
        List<Statistic_1> result = new List<Statistic_1>();
        Statistic_1 stat1 = null;

        int yearstart = DateTime.Today.AddYears(-4).Year;
        int yearend = DateTime.Today.Year;//2014
        string lastGeographischZone = null;

        string query = "SELECT Year ...";

        using (SqlConnection connection = new SqlConnection(Context.db.Connection.ConnectionString))
        {
                ...
   }

这是web.config:

<configuration>
<connectionStrings>
<add name="RMS_DatabaseConnectionString" connectionString="Data Source=****;Initial Catalog=RMS_Database;Persist Security Info=True;User ID=****;Password=****"providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="16384"/>
</system.web>
<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />  
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

<bindings>
  <basicHttpBinding>
    <binding name="basicHttp" allowCookies="true" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000">
      <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/>
    </binding>
  </basicHttpBinding>
  </bindings>
 </system.serviceModel>
 <system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
  <directoryBrowse enabled="true"/>
 </system.webServer>
</configuration>

1 个答案:

答案 0 :(得分:0)

可能问题出在Context.db.Connection.ConnectionString的某个地方。在调试过程中检查它。

相反,尝试使用@ dhaval-patel在他的第二条评论中建议获取propper连接字符串:ConfigurationManager.AppSettings["RMS_DatabaseConnectionString"].ToString()

(您需要添加相应的命名空间才能使用ConfigurationManager:using System.Configuration;