纯 JavaScript 调用 ASP .NET WebService 返回 0
Posted
技术标签:
【中文标题】纯 JavaScript 调用 ASP .NET WebService 返回 0【英文标题】:Pure JavaScript call ASP .NET WebService returns 0 【发布时间】:2018-02-27 12:23:53 【问题描述】:我实现了一个简单的 ASP.NET WebService,并尝试执行函数并获取返回数据。但是 ajax 调用总是返回状态 0 和 responseText 'undefined'。
我将我的 WebService 置于调试模式,我查看了正确发送的数据,但我没有返回。
我看了很多关于 return 0 的帖子,但我没有找到任何解决方案。
有什么问题吗?非常感谢!
网络服务代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace WebServiceDA
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
//inicialização da estrutura do E3DataAccess
E3DATAACCESSLib.E3DataAccessManagerClass E3Da = null;
public WebService1()
//inicializa a conexão com o E3DataAccess
try
E3Da = new E3DATAACCESSLib.E3DataAccessManagerClass();
catch(Exception ex)
Console.Write(ex.ToString());
[WebMethod]
public string HelloWorld()
return "Hello World";
[WebMethod]
public string ReadValue(string ObjectName)
object dt = null, v = null, q = null;
if(E3Da.ReadValue("Dados." +ObjectName, ref dt, ref q, ref v))
return v.ToString();
return "Invalid Object Name";
html 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebService with E3DataAccess</title>
<script type="text/javascript" src="accessWs.js"></script>
</head>
<body>
<h1> WebService E3DataAccess</h1>
<p> Exemplo de um cliente html que acessa métodos de um webservice que contém um E3DataAccess</p>
<div style="background-color:#FFFFFF" id="content">
<span>Tag Name:</span>
<input type="text" name="tagname" id="tagname">
<input type="button" value="Get Tag Value" onclick="CallWs();"
</div>
</body>
</html>
JavaScript 代码:
var ajax;
function CreateAjaxObject()
if(window.XMLHttpRequest) //navegadores modernos
ajax = new XMLHttpRequest();
else if(window.ActiveXObject) //IE antigao
ajax = new ActiveXObject("Msxml2.XMLHTTP");
if(!ajax)
ajax = new ActiveXObject("Microsoft.XMLHTTP");
if(!ajax) //caso não tenha sido iniciado com sucesso
alert("seu navegador não possui suporte");
function SendData(url,dados,AjaxResponseFunction)
CreateAjaxObject();
if(ajax)
//método http
ajax.open("POST",url,true);
//definir o encode do conteúdo
ajax.setRequestHeader('Content-Type',"application/x-www-form-urlencoded");
//tamanho dos dados
ajax.setRequestHeader('Content-Length',dados.length);
//enviar os dados
alert(dados);
ajax.send(dados);
//retorno
ajax.onreadystatechange = function()
if(ajax.readyState==4) //documento está pronto
alert(ajax.status);
AjaxResponseFunction(ajax.status,ajax.ResponseText);
;
function CallWs()
var dados = '';
dados = 'ObjectName=' + encodeURIComponent(tagname.value);
//chamar um webservice = endereço/nomemétodo
SendData('http://localhost:53626/WebService.asmx/ReadValue',dados,AjaxResponseFunction);
function AjaxResponseFunction(status,response)
var divR = document.getElementById('content');
if(ajax.status != 200)
divR.style.backgroundColor = "#FF0000"; //erro vermelho
else
divR.style.backgroundColor = "#FFFFFF"; //ok branco
【问题讨论】:
我会将ajax.send(dados);
移到分配事件处理程序后 (ajax.onreadystatechange
)
我也试试这个。不工作。谢谢!
【参考方案1】:
我找到了解决方案。我在 Web.config 文件中添加了一个简单的代码:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<!-- bellow, code used to fix the security problem-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<!-- end code -->
</system.webServer></configuration>
【讨论】:
以上是关于纯 JavaScript 调用 ASP .NET WebService 返回 0的主要内容,如果未能解决你的问题,请参考以下文章
从 ASP.NET Core Blazor 中的 .NET 方法调用 JavaScript 函数
ASP.NET / JavaScript - Ajax 调用,如何?
如何从 Asp.Net Code Behind 调用 JavaScript 函数?