【问题标题】:using a web service to relay calls to & from another web service in c#在 C# 中使用 Web 服务来中继与另一个 Web 服务之间的调用
【发布时间】:2016-01-19 00:35:00
【问题描述】:

我有一个需要 Windows 身份验证才能使用其 Web 服务的第 3 方应用程序。我还有另一个需要使用这些 Web 服务的 3rd 方应用程序,但是它只能在调用 Web 服务时进行基本身份验证。

我必须创建一个 Web 服务,充当中间人,在两者之间中继请求和响应。有没有比在每次通话中阅读和重建肥皂信息更好/更简单的方法?

【问题讨论】:

    标签: c# .net soap


    【解决方案1】:

    如果这个新的“代理”应用程序只做这一项工作,那么我可能会使用 Windows 服务和 HttpListener。以下是一些帮助您入门的代码:

    static class WebServer {
        private static readonly HttpListener Listener = new HttpListener { Prefixes = { "http://*/" } };
        private static bool _keepGoing = true;
        private static Task _mainLoop;
    
        public static void StartWebServer() {
            if (_mainLoop != null && !_mainLoop.IsCompleted) return;
            _mainLoop = MainLoop();
        }
    
        public static void StopWebServer() {
            _keepGoing = false;
            lock (Listener) {
                //Use a lock so we don't kill a request that's currently being processed
                Listener.Stop();
            }
            try {
                _mainLoop.Wait();
            } catch { /* je ne care pas */ }
        }
    
        private static async Task MainLoop() {
            Listener.Start();
            while (_keepGoing) {
                try {
                    var context = await Listener.GetContextAsync();
                    lock (Listener) {
                        if (_keepGoing) ProcessRequest(context);
                    }
                } catch (Exception e) {
                    if (e is HttpListenerException) return; //this gets thrown when the listener is stopped
                    //handle bad error here
                }
            }
        }
    
        private static void ProcessRequest(HttpListenerContext context) {
            string inputData;
            using (var body = context.Request.InputStream) {
                using (var reader = new StreamReader(body, context.Request.ContentEncoding)) {
                    inputData = reader.ReadToEnd();
                }
            }
            //inputData now has the raw data that was sent
            //if you need to see headers, they'll be in context.Request.Headers
    
            //now you can make the outbound request with authentication here
    
            //send result back to caller using context.Response
        }
    }
    

    另一种选择是使用 ASP.NET Web API 和 IIS,但这会产生很多开销。如果您希望在服务器上运行 IIS,那么这是一个选项。如果没有,我会走 HttpListener 路线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多