简体   繁体   中英

Get location header from response, httpclient

I have current code that is making POST request to REST API:

string url = "https://xxxx.azurewebsites.net/api/walk/";
string sContentType = "application/json";

JObject jsonObject = new JObject();
jsonObject.Add("Duration", walkInfo.Duration);
jsonObject.Add("WalkDate", walkInfo.WalkDate);


HttpClient oHttpClient = new HttpClient();
var oTaskPostAsync = oHttpClient.PostAsync(url, new StringContent(jsonObject.ToString(), Encoding.UTF8, sContentType));

And it works nice, what I have problems with is that I cant figure out how to get Location header from response of API. When I do test requies via postman I can see that location header is set Location → http://xxx/api/walk/5 so I need to get this Location value after PostAsync is executed.

As I have seen in the documentation you need to access to the result that is contained in your variable "oTaskPostAsync".

So for get the Location you should do something like this:

string url = "https://xxxx.azurewebsites.net/api/walk/";
string sContentType = "application/json";

JObject jsonObject = new JObject();
jsonObject.Add("Duration", walkInfo.Duration);
jsonObject.Add("WalkDate", walkInfo.WalkDate);


HttpClient oHttpClient = new HttpClient();
var oTaskPostAsync = oHttpClient.PostAsync(url, new StringContent(jsonObject.ToString(), Encoding.UTF8, sContentType));
var location = oTaskPostAsync.Headers.Location;

Location should return an Uri object.

Note : You have to be careful here, because you are doing an async call, you have to take into account that you probablly won't have the value until the server responds, so you maybe should use "await" for doing it sync.

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