WebAPI:PostAsync与查询字符串不起作用

时间:2016-09-01 13:08:16

标签: asp.net-web-api

请参阅我的示例web api操作,该操作采用一个字符串类型参数。

[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{

        [HttpPost, Route("DeleteCustomer")]
        public HttpResponseMessage DeleteProduct(string customerID)
        {
            HttpResponseMessage response = null;
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                var message = string.Format("No customer found by the ID {0}", customerID);
                HttpError err = new HttpError(message);
                response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                response.ReasonPhrase = message;
            }
            else
            {
                if(repository.Remove(customerID))
                {
                    response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                    response.ReasonPhrase = "Customer successfully deleted";
                }
                else
                {
                    var message = string.Format("Due to some error customer not removed");
                    HttpError err = new HttpError(message);
                    response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                    response.ReasonPhrase = message;
                }
            }


            return response;
        }

}

并使用http客户端以下方式调用,但无法正常工作并发出错误未找到

private void btnDelete_Click(object sender, EventArgs e)
{
    var uri = new Uri(ConfigurationManager.AppSettings["baseAddress"] + "/api/customer/DeleteCustomer");

    var content = new FormUrlEncodedContent(new[] 
    {
        new KeyValuePair<string, string>("customerID", "CUS01")
    });

    try
    {
        using (var client = new HttpClient())
        {
            using (var response = client.PostAsync(uri, content).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show(response.ReasonPhrase);
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                    var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
                    MessageBox.Show(dict["Message"]);
                }
            }
        }
    }
    catch (HttpRequestException ex)
    {
        // catch any exception here
    }            

}

有人请看我的代码并告诉我在调用代码时我犯了哪些错误?感谢

1 个答案:

答案 0 :(得分:0)

[RoutePrefix( “API /客户”)] public class CustomerController:ApiController {

    [HttpPost, Route("DeleteCustomer")]
    public HttpResponseMessage DeleteProduct([FromBody]string customerID)
    {
        HttpResponseMessage response = null;
        Customer customer = repository.Get(customerID);
        if (customer == null)
        {
            var message = string.Format("No customer found by the ID {0}", customerID);
            HttpError err = new HttpError(message);
            response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
            response.ReasonPhrase = message;
        }
        else
        {
            if(repository.Remove(customerID))
            {
                response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                response.ReasonPhrase = "Customer successfully deleted";
            }
            else
            {
                var message = string.Format("Due to some error customer not removed");
                HttpError err = new HttpError(message);
                response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                response.ReasonPhrase = message;
            }
        }


        return response;
    }

}

你能在方法参数中添加[FromBody]关键字吗?