Web Services 使用Web API更新winforms中的记录

bejyjqdl  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(179)

我对实体框架和Web服务还很陌生。
我尝试做是通过调用Web API中update方法从winforms应用程序更新记录Http响应消息返回错误请求,并且不更新任何内容
要么是我在api中写的更新记录的代码有逻辑错误,要么是我在winform中写的代码有逻辑错误。我不知道问题出在哪里。
更新API中的方法

[HttpPut]
public async Task <IActionResult> UpdateStatus ([FromBody]BookStatus entity)
{
    var original = Tools.Context.BookStatus. Find(1);
    Tools.Context.Entry (original).CurrentValues.SetValues (entity);
    var result = await Tools.Context.SaveChangesAsync();

    if (result > 0)
        return Ok (result);

    return Badrequest ();
}

调用更新方法的Winform应用程序

private async void button3_click (object sender,EventArgs e)
{
    BookStatus status = new BookStatus();
    status.IsAvailable = true;
    
    HttpClientHandler clientHandler = new HttpClientHandler();
    clientHandler.ServerCertificateCustomValidationCallback=(sender,cert,chain,sslPolicyError)=>{return true;};
    
    HttpClient client = new HttpClient(clientHandler);
    client.BaseAdress = new Uri ("Https://localhost:5001");
    
    var serialize = JsonConvert.SerializeObject (status);
    var content = new StringContent(serialize,Encoding.UTF8,"application/json");
    var result = await client.PutAsJsonAsync ("api/BookStatus/UpdateStatus",content);
    Message.Text = result.StatusCode.ToString ()";
}
bqf10yzr

bqf10yzr1#

我检查了你的代码,似乎PutAsJsonAsync方法有问题,webapi无法获取bookstatus的值。

我修改了winform客户端中的代码,webapi可以获得值

private  void button1_Click(object sender, EventArgs e)
        {
            BookStatus status = new BookStatus();
            status.Id = 1;
            status.IsAvailable = true;
            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyError) => { return true; };
            HttpClient client = new HttpClient(clientHandler);
            var result1 = client.PutAsJsonAsync<BookStatus>("https://localhost:44318/WeatherForecast", status).Result;
           
        }

结果:

如果您需要有关webapi项目中代码的帮助,可以告诉我项目的更多细节,例如模型类和Dbcontext

相关问题