简体   繁体   中英

Pass request headers through C# app to another service

So I'm currently working on some encoding app that recieves messages (http) then sends it to another service (http). Here is my code:

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;
    }
}

I'm new to C# and kind of stuck on how to pass request headers through my app to client service. I found some info on how to set headers via WebClient, but can't understand how to use it in my case. Also as I know there are some headers that you could not set/modify (like Content-Length)...


Solution. So all I needed was:

// 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);
}

Use Headers property as shown below:

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

According to MSDN, this has been available since: https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx

Apparently a needed something like this:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM