使用HttpClient.PostAsJsonAsync发布标量数据类型

时间:2012-09-21 14:04:19

标签: http-post using dotnet-httpclient

我正在使用HttpClient调用ASP .Net Web API并成功调用操作。此外,我也可以将自定义对象发布到操作中。

现在我面临的问题是,无法发布标量数据类型,如Integer,String等......

以下是我的控制器和调用操作的应用程序代码

//测试调用

的应用程序
[Test]
        public void RemoveCategory()
        {
            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage();

            HttpResponseMessage response = client.PostAsJsonAsync<string>("http://localhost:49931/api/Supplier/RemoveCategory/", "9").Result;

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
        }

// Web API中的控制器和操作

public class SupplierController : ApiController
   {
    NorthwindEntities context = new NorthwindEntities();

    [HttpPost]
    public HttpResponseMessage RemoveCategory(string CategoryID)
    {
    try
    {
    int CatId= Convert.ToInt32(CategoryID);
    var category = context.Categories.Where(c => c.CategoryID == CatId).FirstOrDefault();
    if (category != null)
    {
    context.Categories.DeleteObject(category);
    context.SaveChanges();
    return Request.CreateResponse(HttpStatusCode.OK, "Delete successfully CategoryID = "     +     CategoryID);
    }
    else
    {
    return Request.CreateResponse(HttpStatusCode.InternalServerError, "Invalid     CategoryID");
    }
    }
    catch (Exception _Exception)
    {
    return Request.CreateResponse(HttpStatusCode.InternalServerError, _Exception.Message);
    }
    }

当我在Northwind数据库中发布代表“类别”表的custome对象时,一切正常但我无法发布标量数据,如整数和字符串

当我发布字符串数据类型时,我遇到了异常

  

{“消息”:“找不到与请求URI'http://localhost:49931/api/Supplier/RemoveCategory/'匹配的HTTP资源。”,“MessageDetail”:“在控制器'供应商'上找不到与之匹配的操作请求。“}

任何人都可以指导我吗?

1 个答案:

答案 0 :(得分:5)

您必须将CategoryID参数标记为[FromBody]:

[HttpPost]
public HttpResponseMessage RemoveCategory([FromBody] string CategoryID)
{ ... }

默认情况下,简单类型(如string)将从URI绑定模型。