11

I want to do a web request in a asp.net core project. I tried the following but it doesn't seem to send the data in the request:

using System.Net;

...

//encoder
UTF8Encoding enc = new UTF8Encoding();

//data
string data = "[\"some.data\"]";

//Create request
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Credentials = new NetworkCredential(user, secret);

//Set data in request
Stream dataStream = await request.GetRequestStreamAsync();
dataStream.Write(enc.GetBytes(data), 0, data.Length); 


//Get the response
WebResponse wr = await request.GetResponseAsync();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();

I don't get an error, the request was send but it doesn't seem to send the data with the request. I also can't give the length of the data with the request. Is this a core issue? (ps: The credentials are send correctly)

Can anyone help me?

1
  • 3
    I'm voting to close the question, because it can't be answered (see OP's answer below) Commented Dec 19, 2016 at 16:29

2 Answers 2

1

You may be facing a synchronization context problem. Try to await the asynchronous methods like GetRequestStreamAsync() and GetResponseAsync() instead of getting the Result property.

//Set data in request
Stream dataStream = await request.GetRequestStreamAsync();

//Get the response
WebResponse wr = await request.GetResponseAsync();
Sign up to request clarification or add additional context in comments.

1 Comment

Changed the code. This change did not resolve the problem but is idd more logical (problem was in my api that I was calling see answer below). Thxs for the help!
1

Finally solved it. There was a bug in my external API code where I resolved the API request. The code in my question works (If someone wants to use it).

PS: I edit the code with the remark of ycrumeyrolle

Comments

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.