c# - DeleteAsync和PostAsync不起作用

标签 c# mvvm async-await mvvm-light

我写了这个可以正常工作的PutAsync,可以让我更新数据库中的项目:

private async void Edit()
{
    using (HttpClient client = new HttpClient())
    {
        Item i = new Item();
        i.ID = SelectedItem.ID;
        i.Name = SelectedItem.Name;
        i.Cost = SelectedItem.Cost;

        string json = JsonConvert.SerializeObject(i);

        HttpResponseMessage response = await client.PutAsync("http://localhost:5065/api/item", new StringContent(json, Encoding.UTF8, "application/json"));
        if (response.IsSuccessStatusCode)
        {
            string jsonresponse = await response.Content.ReadAsStringAsync();
            int result = JsonConvert.DeserializeObject<int>(jsonresponse);
            if (result == 2)
            {
                GetItems();
            }
        }
    }
}

现在,我想删除项目并添加新项目,但是此代码似乎不起作用:
public ICommand DeleteCommand
{
    get { return new RelayCommand(Delete); }
}

private async void Delete()
{
    using (HttpClient client = new HttpClient())
    {
        Item i = new Item();
        i.ID = SelectedItem.ID;
        i.Name = SelectedItem.Name;
        i.Cost = SelectedItem.Cost;

        HttpResponseMessage response = await client.DeleteAsync("http://localhost:5065/api/item/" + i.ID );
        if (response.IsSuccessStatusCode)
        {
            string jsonresponse = await response.Content.ReadAsStringAsync();
            int result = JsonConvert.DeserializeObject<int>(jsonresponse);
            if (result == 2)
            {
                GetItems();
            }
        }
    }
}

我的PostAsync也是如此:
private async void New()
{
    using (HttpClient client = new HttpClient())
    {     
        Item i = new Item();
        i.Name = SelectedItem.Name;
        i.Cost = SelectedItem.Cost;

        string json = JsonConvert.SerializeObject(i);

        HttpResponseMessage response = await client.PostAsync("http://localhost:5065/api/item", new StringContent(json, Encoding.UTF8, "application/json"));
        if (response.IsSuccessStatusCode)
        {
            string jsonresponse = await response.Content.ReadAsStringAsync();
            int result = JsonConvert.DeserializeObject<int>(jsonresponse);
            if (result == 2)
            {
                GetItems();
            }
        }
    }
}

我得到以下回应:
{StatusCode: 204, ReasonPhrase: 'No Content', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{  Pragma: no-cache  X-SourceFiles: =?UTF-8?B?RDpcU0NIT09MXE5NQ1QgTGFhdHN0ZVxCdXNpbmVzcyBhcHBsaWNhdGlvbnNcUFJPSkVDVFxQcm9qZWN0XFByb2plY3QuYXBpXGFwaVxwcm9kdWN0XDU=?=  Cache-Control: no-cache  Date: Mon, 19 Jan 2015 13:48:32 GMT  Server: Microsoft-IIS/8.0  X-AspNet-Version: 4.0.30319  X-Powered-By: ASP.NET  Expires: -1}}

我做错了什么,我该如何进行发布和删除工作?

编辑:
这是Delete void的一些服务器端代码,非常基本:
public static int DeleteItem(int id)
        {
            int rowsaffected = 0;
            DbTransaction trans = null;

            try
            {
                trans = Database.BeginTransaction("ConnectionString");

                string sql = "DELETE FROM Item WHERE ID=@ID";
                DbParameter par1 = Database.AddParameter("ConnectionString", "@ID", id);
                rowsaffected += Database.ModifyData(trans, sql, par1);

                trans.Commit();
            }
            catch (Exception ex)
            {
                if (trans != null)
                    trans.Rollback();
            }
            finally
            {
                if (trans != null)
                    Database.ReleaseConnection(trans.Connection);
            }

            return rowsaffected;
        }

我在这里称呼它:
   // DELETE: api/Item/5
        public void Delete(int id)
        {
            ItemDataAccess.DeleteItem(id);
        }

编辑:
也许一些额外的信息,在下一行
int result = JsonConvert.DeserializeObject<int>(jsonresponse);

在两种情况下,我都会收到此错误:
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.

最佳答案

您的调用成功,204是一个成功代码,告诉客户不要在体内获取任何数据。您没有从消息中返回任何内容,因此服务器会在204中自动填充Controller方法中的void类型。

关于c# - DeleteAsync和PostAsync不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026201/

相关文章:

c# - PdfSharpCore 图像渲染问题

mvvm - 为用户输入暂停 View 模型进程

c# - 'call command on property change' 功能应该去哪里?

c# - HttpClient.GetAsync 立即抛出 TaskCanceledException

c# - C# 中的 Async Func - 正确的 async await 用法

c# - 注册 免费 COM Interop : The application has failed to start because its side-by-side configuration is incorrect

c# - 如何在 MVC Controller 中使用消息框?

c# - 如何创建不返回的 C# 委托(delegate)?

带有 Reactive Cocoa 的 iOS MVVM,UITextField 返回信号和条件 : how to improve my code

c# - 异步提交或回滚事务范围