2011-12-13 3 views
0

, поэтому у меня есть некоторые проблемы. Цель проблемы заключается в том, что когда я пытаюсь вызвать веб-службу из User Control с помощью Ajax, я получил 500 Internal Server Error.ASP.NET - вызов веб-службы из пользовательского элемента управления (.Ascx) Возвращает ошибку 500 Внутренняя ошибка сервера

Существует мой пример кода:

Web Service .cs

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.Services; 


[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 

public class BudgetJson : System.Web.Services.WebService { 

    public BudgetJson() 
    { 
    } 



    [WebMethod] 
    public static String GetRecordJson() 
    { 
     return " Hello Master, I'm Json Data "; 
    } 
} 

управления пользователя (.ascx) Файл (Ajax вызова)

$(document).ready(function() { 
      $.ajax({ 
       type: "POST", 
       url: "BudgetJson.asmx", 
       data: "{}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (msg) 
       { 
        alert(msg); 
       } 
      }); 
     }); 

Таким образом, при загрузке страницы и запрос отправлен, я получил такой ответ:

soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlTextReader.Read() at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read() at System.Xml.XmlReader.MoveToContent() at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent() at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement() at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest() at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message) at System.Web.Services.Protocols.SoapServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response) at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) --- End of inner exception stack trace ---

Если я добавлю имя метода в URL, я получил такую ​​ошибку:

Unknown web method GetRecordJson. Parameter name: methodName Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Unknown web method GetRecordJson. Parameter name: methodName

Любое решение?

ответ

2

Пара вещей на стороне сервера:

Метод не должен быть статичным. Это относится только к «страницам» на страницах ASPX.

Во-вторых, вам нужно украсить класс службы атрибутом [ScriptService], чтобы иметь возможность связываться с ним в JSON, который, как я предполагаю, вы, вероятно, захотите сделать, поскольку вы используете jQuery.

[ScriptService] 
public class BudgetJson : System.Web.Services.WebService { 
    [WebMethod] 
    public String GetRecordJson() 
    { 
    return " Hello Master, I'm Json Data "; 
    } 
} 

На стороне клиента, вам нужно указать, какой метод вы хотите выполнить в вашем $.ajax() URL:

$.ajax({ 
    type: "POST", 
    url: "BudgetJson.asmx/GetRecordJson", 
    data: "{}", 
    // The charset and dataType aren't necessary. 
    contentType: "application/json", 
    success: function (msg) { 
    alert(msg); 
    } 
}); 

Вы также можете упростить $.ajax() Usage немного, как показано выше. charset isn't necessary and jQuery automatically detects the dataType из заголовков, отправленных с сервера.

+0

По-прежнему такая же ошибка ... –

+0

@AlekoGharibashvili Была проблема со стороны клиента, которую я пропустил изначально. Обновлен мой ответ. –

+0

Также обновленный клиентский скрипт, но ничего нового, работает ли этот код на вашей машине? есть ли какие-то проблемы с конфигурацией? если этот код работает на вашем компьютере, поделитесь своим файлом web.config ... –

Смежные вопросы