C# 如何调用WebMethod?
我试图从JavaScript调用C# 如何调用WebMethod?,c#,javascript,exception-handling,asmx,C#,Javascript,Exception Handling,Asmx,我试图从JavaScript调用WebMethod。到目前为止,我已经: EMSWebService.asmx: namespace EMSApplication.Web.WebServices { /// <summary> /// Holds the Webservice methods of EMSApplication </summary> [WebService(Namespace = "http://tempuri.org/")
WebMethod
。到目前为止,我已经:
EMSWebService.asmx:
namespace EMSApplication.Web.WebServices
{
/// <summary>
/// Holds the Webservice methods of EMSApplication
</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class EMSWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
我已经编写了
System.Diagnostics.Debug.WriteLine(“helloworld”)
在WebMethod
中,它正在执行,即,它正在Visual Studio的输出窗口中打印“Hello World”,但我没有收到任何警告消息。您需要确保在web.config中定义了scripthandlerfactory……这里有更多信息。我想直接回答这个问题
我有一个WebMethod
,位于SomePage.aspx
文件中:
[WebMethod]
public static String DoSomething(String shiftName)
{
return shiftName+" hi there";
}
问题是:如何调用此web方法?因为这是HTTP,所以答案是向服务器发送HTTP:
POST http://localhost:53638/SomePage.aspx/DoSomething HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: qps-ploc,en-US;q=0.5
Accept-Encoding: gzip, deflate
Host: localhost:53638
Connection: Keep-Alive
Content-Length: 23
Content-Type: application/json;charset=utf-8
{'shiftName':'contoso'}
重要的注意事项包括:
- HTTP方法:
(POST
将不起作用)GET
- 您可以在aspx页面上将方法的名称指定为SomePage.aspx/[MethodName]。在这种情况下: SomePage.aspx/DoSomething
- 将方法的参数作为JSON传递。此方法有一个字符串参数:
。这意味着我构建了JSON:shiftName
{'shiftName':'contoso'}
- 对于请求的JSON内容类型,您必须指定
请求头:内容类型
ContentType: application/json;charset=utf-8
hi
,并返回该字符串,那么web服务器的响应是:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 24
Connection: Close
{"d":"contoso hi there"}
其中HTTP响应主体也是一个JSON字符串,具有一个名为d
的属性。我不知道他们从哪里得到的d
,但它就在那里
这就是使用http(例如汇编语言、COM、C#、Java、Delphi)调用WebMethod的方式
最常见的问题是如何使用jQuery从客户端调用它
注意:发布到公共域的任何代码。无需归因
在客户端设置一个断点,例如在Google Chrome优秀的开发工具中,查看ajax调用前后发生了什么。你能验证scripthandlerfactory是否在web.config中定义吗?不,我没有在web.config中定义任何scripthandlerfactory。我该怎么办?请看这里,这一页讨论了从脚本调用Web服务需要做些什么。@JeremyHoward你能发布你的答案吗。这样我就可以接受了。在
的
中使用
后解决此问题。非常感谢,谢谢。您能告诉我[WebService(命名空间=“Tapas,您服务的命名空间是为您服务的使用者提供一个唯一的服务位置。这是为了防止服务名称相同时发生冲突。在投入生产之前,您希望将命名空间更改为更独特的名称。有关此主题的详细信息,请参阅此处…”。。。
{'shiftName':'contoso'}
ContentType: application/json;charset=utf-8
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 24
Connection: Close
{"d":"contoso hi there"}
$.ajax({
type: "POST",
url: 'Catalogo.aspx/checaItem',
data: "{ id : 'teste' }",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});