类别:程序开发

日期:2022-06-07 浏览:444 评论:0

由于医院环境需要,所有院内客户机无法连接医院前置服务器的WebService和一般处理程序,客户机只能通过院内服务器做中转,跳转到前端服务器WebService和一般处理程序上。

解决方案:

1、创建一个中转的一般处理程序

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace WebApplication
{
    /// <summary>
    /// AjaxHandler 的摘要说明
    /// </summary>
    public class AjaxHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string action = "GetAjaxPost";
            context.Response.ContentType = "text/plain";
            switch (action)
            {
                case "GetAjaxPost": GetAjaxPost(context);  //Post提交
                    break;
                case "GetAjaxGet": GetAjaxGet(context);  //Get提交
                    break;
                case "GetVs": GetVs(context);  //测试
                    break;
            }           
        }
        public void GetVs(HttpContext context)
        {
            string name = context.Request["name"].ToString();
            context.Response.Write("1" + "name=" + name);
        }

        public void GetAjaxGet(HttpContext context)
        {
            string url = string.Empty;
            StringBuilder sb = new StringBuilder();
            foreach (string key in context.Request.Params.AllKeys)
            {
                if (key == "HostUrl")
                {
                    url = context.Request.Params[key];
                }
                else
                {
                    if (key == "username")
                    {
                        break;
                    }
                    sb.Append(string.Format("&{0}={1}", key, context.Request.Params[key]));
                }
            }
            string msg = sb.ToString().Substring(1, sb.Length - 1);
            GetValue(url, msg, context);
        }

        public void GetAjaxPost(HttpContext context)
        {
            string url = string.Empty;
            foreach (string key in context.Request.Params.AllKeys)
            {
                if (key == "HostUrl")
                {
                    url = context.Request.Params[key];
                }
            }
            GetValue(url, context);
        }

        //中间库Get提交
        public void GetValue(string apiUrl, string queryString, HttpContext context)
        {
            string responseString = string.Empty;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(apiUrl + "?" + queryString);
            request.ContentType = "text/html";
            request.Method = "POST";
            request.ContentLength = queryString.Length;
            request.Timeout = 20000;
            byte[] bytes = Encoding.UTF8.GetBytes(queryString);
            Stream os = null;
            try
            { // send the Post
                request.ContentLength = bytes.Length;   //Count bytes to send
                os = request.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         //Send it
            }
            catch (WebException ex)
            {
                throw ex;
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseString = reader.ReadToEnd();
                }
            }
            catch (Exception ex2)
            {
                throw ex2;
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
            context.Response.Write(responseString);
        }

        //中间库Post提交
        public void GetValue(string apiUrl, HttpContext context)
        {
            string responseString = string.Empty;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(apiUrl);
            request.ContentType = "application/x-www-form-urlencoded;charset:utf-8";
            request.Method = "POST";


            StringBuilder paraStrBuilder = new StringBuilder();
            foreach (string key in context.Request.Params.AllKeys)
            {
                paraStrBuilder.AppendFormat("{0}={1}&", key, context.Request.Params[key]);
            }
            string para = paraStrBuilder.ToString();
            if (para.EndsWith("&"))
                para = para.Remove(para.Length - 1, 1);
            byte[] bt = Encoding.UTF8.GetBytes(para);
            string responseData = String.Empty;
            request.ContentLength = bt.Length;
            //GetRequestStream 输入流数据
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(bt, 0, bt.Length);
                reqStream.Close();
            }
          
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Stream stream = response.GetResponseStream();
                using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
                {
                    responseString = streamReader.ReadToEnd().ToString();
                }
            }
            context.Response.Write(responseString);
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

2、创建中转WebService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using WebApplication.Models;

namespace WebApplication
{
    /// <summary>
    /// WebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public string AjaxWebService(string url, string action, string strArgs)
        {
            string[] argsArray = strArgs.Split('$');
            string[] args = new string[argsArray.Length];

            for (int i = 0; i < argsArray.Length; i++)
            {
                args[i] = argsArray[i];
            }
            object result = WSHelper.InvokeWebService(url, action, args);
            return result.ToString();

        }
    }
}

3、测试过程和数据

测试调用的一般处理程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"].ToString();
            context.Response.ContentType = "text/plain";
            switch (action)
            {
                case "GetVs": GetVs(context);
                    break;
            }
        }
        public void GetVs(HttpContext context)
        {
            string name = context.Request["name"].ToString();

            context.Response.Write("1" + "name=" + name);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

测试调用的WebService

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

namespace WebApplication
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(string name,string text)
        {
            return "参数内容1:" + name + "   参数内容2:" + text;
        }
    }
}

调用中转WebSerivce 和 一般处理程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.Models;

namespace WebApplication
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            //中转WebService地址
            string url = "http://localhost:2064/WebService.asmx";
            //中转WebService参数
            string[] args = new string[3];
            args[0] = "http://localhost:2064/WebService1.asmx";  //前端WebService地址
            args[1] = "HelloWorld";  //前端WebService需调用函数
            args[2] = "abc$text"; // 前端所需要的参数
            object result = WSHelper.InvokeWebService(url, "AjaxWebService", args);
            string msg = result.ToString();


            //显示页面

            msgshow.InnerText = msg;
        }
    }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication.index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="JS/jquery-1.8.2.min.js"></script>
    <title></title>
<script type="text/javascript">
          $(function(){
              $.ajax({
                  url: "/AjaxHandler.ashx",
                  data: { HostUrl: "http://localhost:2064/Handler1.ashx", action: "GetVs", name: "aa" },
                  type: "post",
                  async:false,
                  dataType: "text",
                  success: function (data) {
                      alert(data);
                  }
              });
          });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="msgshow" runat="server">
    
    </div>
    </form>
</body>
</html>

4、用到的类库WSHelper

using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Services.Description;

namespace WebApplication.Models
{
    public static class WSHelper
    {
        #region InvokeWebService
        /// < summary>     
        /// 动态调用web服务     
        /// < /summary>     
        /// < param name="url">WSDL服务地址< /param>     
        /// < param name="methodname">方法名< /param>     
        /// < param name="args">参数< /param>     
        /// < returns>< /returns>     
        public static object InvokeWebService(string url, string methodname, object[] args)
        {
            return WSHelper.InvokeWebService(url, null, methodname, args);
        }

        /// < summary>     
        /// 动态调用web服务     
        /// < /summary>     
        /// < param name="url">WSDL服务地址< /param>     
        /// < param name="classname">类名< /param>     
        /// < param name="methodname">方法名< /param>     
        /// < param name="args">参数< /param>     
        /// < returns>< /returns>     
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
            if ((classname == null) || (classname == ""))
            {
                classname = WSHelper.GetWsClassName(url);
            }

            try
            {
                //获取WSDL     
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码     
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider icc = new CSharpCodeProvider();

                //设定编译参数     
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类     
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法     
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return mi.Invoke(obj, args);

                /*    
                PropertyInfo propertyInfo = type.GetProperty(propertyname);    
                return propertyInfo.GetValue(obj, null);    
                */
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }

        private static string GetWsClassName(string wsUrl)
        {
            string[] parts = wsUrl.Split('/');
            string[] pps = parts[parts.Length - 1].Split('.');
            return pps[0];
        }
        #endregion
    }
}


本文标题:C# 中转WebService和一般处理程序
本文链接:https://vtzw.com/post/1012.html
作者授权:除特别说明外,本文由 零一 原创编译并授权 零一的世界 刊载发布。
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。
 您阅读本篇文章共花了: 

 可能感兴趣的文章

评论区

发表评论 / 取消回复

必填

选填

选填

◎欢迎讨论,请在这里发表您的看法及观点。

最新留言