Asp .net Core 中的 HTTPClient 上的 Post 请求响应 500

问题描述 投票:0回答:1

请求回复:

{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
}}

这里我请求一个 .netCore Web API 来保存用户信息。我在本地 IIS 中托管了一个 API,当我调用

GetUserList
方法时,它可以工作,但是当我使用
SaveUser
调用
POSTAsync
方法时,它会提供以下错误。请帮我解决这个问题。 我的请求方式:

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");
        }

这里我添加了API控制器方法

API方法包含以下代码:

[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);                      
        }
asp.net-core dotnet-httpclient webapi postasync
1个回答
1
投票

最好使用

client.PostAsJsonAsync
,因为它会自动为您转换为
json
。您将按如下方式实施您的发布请求:

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);
© www.soinside.com 2019 - 2024. All rights reserved.