Request Response:
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Transfer-Encoding: chunked
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Mon, 03 Oct 2022 06:47:30 GMT
}}
Here I am requesting an .netCore Web API for saving user information. Where I have Hosted an API in local IIS and its working when I am calling a GetUserList method. but when I am calling SaveUser method with POSTAsync its provide below error. Please help me about this issus. My request Method:
public async Task<IActionResult> SaveUser(string name, string email, string mobile, string address, string passwrod,
string userrole)
{
User usernew = new User();
usernew.Name = name;
usernew.Email = email;
usernew.Mobile = mobile;
usernew.Address = address;
usernew.Password = passwrod;
usernew.UsrRoleId = 1;
var json2 = JsonConvert.SerializeObject(usernew);
HttpContent postContent = new StringContent(json2, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(burl "User/SaveUser", postContent);
if (response.IsSuccessStatusCode)
{
}
else
{
}
return Redirect("Index");
}
Here I have added API Controller method
API Method contains this code
[HttpPost]
[Route("SaveUser")]
[Consumes("application/json")]
public IActionResult SaveUser(User user)
{
User us = new User();
us.Name = user.Name;
us.Email =user.Email;
us.Mobile = user.Mobile;
us.Address = user.Address;
us.Password = PasswordEnc(user.Password);
_UserRepository.SaveUser(us);
return Ok(true);
}
CodePudding user response:
It is better to use client.PostAsJsonAsync
as it automatically does the conversion for you to json
. You would implement your post request as below:
User usernew = new User();
usernew.Name = name;
usernew.Email = email;
usernew.Mobile = mobile;
usernew.Address = address;
usernew.Password = passwrod;
usernew.UsrRoleId = 1;
var result = await client.PostAsJsonAsync(burl "User/SaveUser", usernew);