65.9K
CodeProject 正在变化。 阅读更多。
Home

远程脚本 - 使用 JavaScript 和 C# 调用 WebService

2005年2月18日

2分钟阅读

viewsIcon

296796

downloadIcon

5026

使用 JavaScript 调用 WebService。通过使用本地 asmx 作为代理函数并避免在 JavaScript 中显示 webservice URI 来实现安全性。

引言

过去两年我一直在使用 webservice,但每当我使用一个函数时,我必须回发我的所有页面。使用远程脚本,我们可以使用 JavaScript 从客户端调用我们的 webservice,而无需回发所有页面内容,只需一条指令。我们发送该行,捕获结果并显示它。我们不需要回发,操作在后台处理,对用户来说是隐形的,并且像“行来行往”一样快速。

<script language="JavaScript">
init(){
 service.useService("https:///CursoAspNetWebService/Service1.asmx?WSDL",_
                                                                     "Service1"); 
}
function tst(){ 
   iCallID = service.Service1.callService("Suma",ip1.value,ip2.value); 
}
function onmyresult(){ 
   service.innerHTML= "Resultado : " + event.result.value; 
} 
</script>
<body onLoad="init();">
  <button onclick="javascript:tst()" ID="Button1">Call Add Web Method</button>
  <div id="service" style="BEHAVIOR:url(webservice.htc)" onresult="onmyresult();">
  </div>
</body>

源代码包括用于的 webservice.htc,即使用的 HTML 组件。

HTML

我们需要使用纯 HTML 控件创建一个界面,因为我们不想将页面发送到服务器。我们只需要一个文本和一个带有功能的按钮

onclick="doSuma(texta.value,textb.value)

以及我们想要显示结果的部分,例如一个 <Div>

id="service" style="BEHAVIOR: url(webservice.htc)"

Init 脚本

我们需要在 HTML 的加载中放入 init(),并且通过单击该按钮调用函数 doSuma(...)

function init() { 
    service.useService("proxy.asmx?WSDL","proxy"); 
}
function doSuma(y, x){ 
    oSPAN.innerText = y + " + " + x + " = "; 
    iCallID = service.proxy.callService(myResults, "Adicion", y,x); 
}

iCallID 是一个 var,稍后未被使用,但结果来自其调用。我们需要填写参数

  1. 调用一个函数来管理结果
  2. 调用 public 函数
  3. 从第 3rd 个值开始,发送要处理的值,到所需的必要值

MyResult JavaScript 函数

function myResults(result){ 
    if(result.error){ 
        var xfaultcode = result.errorDetail.code; 
        var xfaultstring = result.errorDetail.string; 
        var xfaultsoap = result.errorDetail.raw; 
        oSPAN.innerText = xfaultcode + " " + xfaultstring + " " + xfaultsoap;
    }
    else{ 
        oSPAN.innerText += result.value; 
    } 
} //the end of function

本地代理

本地代理的目标是为应用程序提供安全性。 我们已经在 JavaScript 中看到,一个 URI 指向 localhost。 如果我们不在 localhost 中使用代理,则需要提供 webservice 的完整 URI,并且我们会向其他用户敞开大门。 在这种情况下,我们可以在 ASP.NET 中通过表单级别保护应用安全性。

代理只有一个真实 web 服务的实例和一个函数的单一调用

using System;
using System.Web;
using System.Web.Services;

namespace RemoteScriptingDemo1
{
 public class proxy : System.Web.Services.WebService
 {
  public proxy()
  {
   InitializeComponent();
  }

  private IContainer components = null;
    
  private void InitializeComponent()
  {
  }

  protected override void Dispose( bool disposing )
  {
   if(disposing && components != null)
   {
    components.Dispose();
   }
   base.Dispose(disposing);  
  }  

  [WebMethod]
  public decimal Adicion(decimal x, decimal y)
  {
   WSDemo.Service1 ws = new RemoteScriptingDemo1.WSDemo.Service1();
   return ws.suma(x,y);
  }
 }
}

许可证

本文未附加明确的许可证,但可能在文章文本或下载文件本身中包含使用条款。如有疑问,请通过下面的讨论区联系作者。

作者可能使用的许可证列表可以在此处找到。

© . All rights reserved.