我有第三方应用程序,需要Windows身份验证才能使用其Web服务。我还有另一个需要使用这些Web服务的第三方应用程序,但是它只能在调用Web服务时进行基本身份验证。
我必须创建一个Web服务,充当中间人,将中继两者之间的请求和响应。有没有比在每次通话中阅读和重建肥皂信息更好/更简单的方法?
答案 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路线。