使用网络服务将呼叫转发到&来自c#中的其他Web服务

时间:2016-01-18 15:54:18

标签: c# .net soap

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

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

1 个答案:

答案 0 :(得分:0)

如果这个新的“代理”应用程序只执行这一项工作,那么我可能会使用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路线。

相关问题