对 ASP 服务的 AJAX 调用抛出 500 - 缺少什么?



我有几个web应用程序可以正常工作,但由于某种原因,每当我调用服务中的函数时,这个应用程序都会返回500个错误。

以下是web.config文件:

<configuration>
  <connectionStrings>
    <add name="MyData" connectionString="** Insert Connection String Here **" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="10" />
    </authentication>
    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" 
             type="System.Web.Security.SqlMembershipProvider" 
             connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" 
             enablePasswordReset="true" 
             requiresQuestionAndAnswer="false" 
             requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" 
             minRequiredPasswordLength="6" 
             minRequiredNonalphanumericCharacters="0" 
             passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" 
             type="System.Web.Profile.SqlProfileProvider" 
             connectionStringName="ApplicationServices" 
             applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" 
             type="System.Web.Security.SqlRoleProvider" 
             connectionStringName="ApplicationServices" 
             applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" 
             type="System.Web.Security.WindowsTokenRoleProvider" 
             applicationName="/" />
      </providers>
    </roleManager>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <!-- system.serviceModel added by developers -->
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="RestJson">
          <enableWebScript />
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="WebTestBehavior">
          <!-- ** serviceMetadata httpGetEnabled="true" / ** -->
          <!-- serviceDebug includeExceptionDetailInFaults="true" / -->
        </behavior>
        <behavior name="">
          <!-- ** serviceMetadata httpGetEnabled="true" / ** -->
          <!-- serviceDebug includeExceptionDetailInFaults="false" / -->
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="BasicBinding">
          <!-- ** Change from "None" ** -->
          <security mode="TransportCredentialOnly" />
        </binding>
      </webHttpBinding>
    </bindings>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
                               multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Web_Test.LoginService" 
               behaviorConfiguration="WebTestBehavior">
        <endpoint address="" 
                  binding="webHttpBinding" 
                  bindingConfiguration="BasicBinding"
                  name="RestJson" 
                  contract="Web_Test.LoginServiceInterface" 
                  behaviorConfiguration="RestJson">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
      </service>
    </services>
  </system.serviceModel>
</configuration>

以下是我的main.cs.html中调用该服务的Javascript代码://userUsername和userPassword是字符串变量

var TestConnectionParams = [{"username": userUsername, "password": userPassword}];
$.ajax({
    type: "POST",
    url: "/LoginService.svc/TestConnection",
    data: JSON.stringify(TestConnectionParams),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        var ReturnString = "Login returned " + data;
        $(OutputDiv).html(ReturnString);
    },
    error: function (HelpRequest, ErrorCode, TheError) {
        var ErrorMsg = "Login Failed:<br />" + TheError;
        $(OutputDiv).html(ErrorMsg);
    },
    async:false
});

这是该服务的.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Configuration;
namespace Web_Test
{
    [ServiceContract]
    public interface LoginServiceInterface
    {
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        String TestConnection(String username, String password);
    }
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class LoginService : LoginServiceInterface
    {
        public String TestConnection(String username, String password)
        {
            String ReturnString = "This didn't do anything";
            return ReturnString;
        }
    }
}

AJAX调用返回"登录失败:内部服务器错误"。

我很确定我在web.config中遗漏了一些相当明显的东西,但我看不到。

THWACK-gee,你不认为服务的.cs文件中的函数需要两个字符串,而AJAX调用正在向它发送一个单元素数组(其中元素由两个字符串组成(,这与它有关系,是吗?

对于那些将来可能有这个问题的人,更正后的.svc.cs是:

namespace Web_Test
{
    public struct TestConnectionParams
    {
        public String username;
        public String password;
    }
    [ServiceContract]
    public interface LoginServiceInterface
    {
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        String TestConnection(TestConnectionParams[] theParams);
    }
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class LoginService : LoginServiceInterface
    {
        public String TestConnection(TestConnectionParams[] theParams)
        {
            String ReturnString = "Username is '" + theParams[0].username + ' and Password is {wouldn't you like to know}";
            // actually, password is theParams[0].password
            return ReturnString;
        }
    }
}

最新更新