通过C#应用程序将请求标头传递到另一个服务

时间:2019-10-09 09:13:47

标签: c# proxy header httprequest

因此,我目前正在开发一些编码应用程序,该应用程序接收消息(http),然后将其发送到另一个服务(http)。这是我的代码:

public class MyRequestsController : ApiController {

    public class ConnToSys {

        public HttpResponseMessage MakeRequest(HttpContent request, string path) {

            string URL = "http://" + ConfigurationManager.AppSettings["systemHost"] + ":" + ConfigurationManager.AppSettings["systemPort"] + path;

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            HttpResponseMessage response = client.PostAsync(URL, request).Result;
            if (!response.IsSuccessStatusCode) {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            client.Dispose();

            return response;
        }
    }

    // get POST http request from Client
    public HttpResponseMessage Post(HttpRequestMessage request) {

        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        string path = request.RequestUri.AbsolutePath;
        // then send it's content to another Service
        try {
            // some encoding here
            ...
            // send encoded request to system
            ConnToSys connection = new ConnToSys();
            response = connection.MakeRequest(BinRequest, path);
        }
        catch (Exception ex) {
            ...
        }

        // some decoding here
        ...

        // and return it back to Client
        return response;
    }
}

我是C#的新手,对如何将请求标头通过我的应用程序传递给客户端服务有点困惑。我找到了一些有关如何通过WebClient设置标头的信息,但无法理解在我的情况下如何使用标头。另外,据我所知,有些标头无法设置/修改(例如Content-Length)...


解决方案。所以我所需要的只是:

// get request headers
string sHeaders = request.Headers.ToString();

// pass headers to Connection function
response = connection.MakeRequest(BinRequest, path, sHeaders);

// set headers for request
foreach (var raw_header in headers.Split(new[] { "\r\n" }, 
StringSplitOptions.RemoveEmptyEntries)) {
    var index = raw_header.IndexOf(':');
    if (index <= 0)
        continue;

    var key = raw_header.Substring(0, index);
    var value = index + 1 >= raw_header.Length ? string.Empty : 
    raw_header.Substring(index + 1).TrimStart(' ');
    client.DefaultRequestHeaders.TryAddWithoutValidation(key, value);
}

2 个答案:

答案 0 :(得分:0)

使用Headers属性,如下所示:

request.Headers["X-My-Custom-Header"] = "the-value";

根据MSDN,此功能自https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx

开始可用

答案 1 :(得分:0)

显然需要这样的东西:

public HttpResponseMessage MakeRequest(HttpContent request, String path, String headers) {

...

// set headers 
foreach (var raw_header in headers.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) {
    var index = raw_header.IndexOf(':');
    if (index <= 0)
        continue;

    var key = raw_header.Substring(0, index);
    var value = index + 1 >= raw_header.Length ? string.Empty : raw_header.Substring(index + 1).TrimStart(' ');
    client.DefaultRequestHeaders.TryAddWithoutValidation(key, value);
}

...

// get request headers
string sHeaders = request.Headers.ToString();

...

response = connection.MakeRequest(BinRequest, path, sHeaders);