Reputation: 305
I'm quite noob into asp.net
I'm building a simple solution in VS2019, using asp.net MVC, which is supposed to send a User data to another API which will be responsible for saving into database.
So far, both APIs are REST and I'm not using core
Basically, it is a form with a submit that will POST to the external project, pretty simple. I'm following some tutorials and stuff but there are so many different ways that got me confused, so I decided to ask here
Here's what I have so far
[HttpPost]
public async ActionResult Index(User user)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://pathtoAPI.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
User newuser = new User()
{
email = user.email,
nome = user.nome,
cpf = user.cpf,
cnpj = user.cnpj,
userName = user.userName,
senha = user.senha,
telefone = user.telefone
};
var jsonContent = JsonConvert.SerializeObject(newuser);
var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");
contentString.Headers.ContentType = new
MediaTypeHeaderValue("application/json");
//contentString.Headers.Add("Session-Token", session_token);
HttpResponseMessage response = await client.PostAsync("register", contentString);
return Content($"{response}");
}
I want to receive the "OK" message from the other API and just print it on my screen, I'm using the cshtml
file to handle the front and the form as well.
The return though seems to be wrong, it's expecting either 'null, task, task, or something like.
Can someone please help me with this code?
Thanks
Upvotes: 0
Views: 1026
Reputation: 2471
You need to return the content of the response, not the response object itself.
HttpResponseMessage response = await client.PostAsync("register", contentString);
string responseBody = await response.Content.ReadAsStringAsync();
return Content(responseBody);
Upvotes: 1