2

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 can't figure out how to get Location header from response of API. When I do test requires 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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would convert all the async/await part in Bold. Or the whole Note. Can also be written as var location = oTaskPostAsync.Headers.GetValues("Location").FirstOrDefault().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.