如何正确使用PUT更新某些内容?

时间:2018-09-06 03:40:45

标签: c# rest asp.net-web-api2

我正在尝试学习xamarin形式。我有一个现有的数据库,希望通过App进行访问。在这里,我想使用Web api / REST更新某些内容,我遵循了this指南来使用REST。不幸的是,它不起作用,我什至不知道为什么。 如何正确使用PUT更新某些内容,这是什么地方出了错?

WEB API类:

class GuestAcc
{
    public string RefCode { get; set; }
    public double Price { get; set; }
}

Xamarin模型:

public class GuestAcc
{
    public string RefCode { get; set; }
    public double Price { get; set; }
}

GuestAccountsController:

[ResponseType(typeof(void))]
    public async Task<IHttpActionResult> UpdateBalance(GuestAcc guestAcc)
    {
        var guestAccounts = db.GuestAccounts.First(x => x.ReferenceCode == guestAcc.RefCode);
        guestAccounts.Balance = guestAccounts.Balance - guestAcc.Price;
        db.Entry(guestAccounts).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return StatusCode(HttpStatusCode.NoContent);
    }

Xamarin形式:

 private async void btn_proceed_clicked(object sender, EventArgs e)
 {
            GuestAcc guestAcc = new GuestAcc();
            guestAcc.Price = 125;
            guestAcc.RefCode = "user123";
            var guestAccountURL = "http://192.168.8.100:56750/api/UpdateBalance/";
            var uri_guestAccount = new Uri(string.Format(guestAccountURL, string.Empty));
            var json = JsonConvert.SerializeObject(guestAcc);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;

            response = await client.PutAsync(uri_guestAccount, content);
            if (response.IsSuccessStatusCode)
            {
                await DisplayAlert("Notice", "Success", "Ok");
            }
 }

1 个答案:

答案 0 :(得分:1)

您需要在操作名称中或作为方法的属性使用正确的HTTP动词。像

[ResponseType(typeof(void))]
[HttpPut]
public async Task<IHttpActionResult> UpdateBalance(GuestAcc guestAcc)
{
    var guestAccounts = db.GuestAccounts.First(x => x.ReferenceCode == guestAcc.RefCode);
    guestAccounts.Balance = guestAccounts.Balance - guestAcc.Price;
    db.Entry(guestAccounts).State = EntityState.Modified;
    await db.SaveChangesAsync();
    return StatusCode(HttpStatusCode.NoContent);
}

或以类似的名称

[ResponseType(typeof(void))]    
public async Task<IHttpActionResult> PutBalanceAsync(GuestAcc guestAcc)
{
    var guestAccounts = db.GuestAccounts.First(x => x.ReferenceCode == guestAcc.RefCode);
    guestAccounts.Balance = guestAccounts.Balance - guestAcc.Price;
    db.Entry(guestAccounts).State = EntityState.Modified;
    await db.SaveChangesAsync();
    return StatusCode(HttpStatusCode.NoContent);
}