2012-09-21 31 views
1

我使用HttpClient調用ASP .Net Web API併成功調用動作。另外我也可以將自定義對象投入使用。Post標量數據類型使用HttpClient.PostAsJsonAsync

現在我面臨的問題是,無法發佈一樣整數,字符串等標量數據類型...

下面是我的控制器和應用程序代碼調用該調用操作

//測試應用程序

[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數據庫正常工作,但所有的事情,我無法發表像Integer和String

標量數據

當我交的字符串數據類型,我得到以下異常

custome對象

{「消息」:「沒有HTTP資源發現該請求URI‘http://localhost:49931/api/Supplier/RemoveCategory/’相匹配。」,「MessageDetail」:「無動作被在控制器‘供應商’與請求匹配找到」}

Can an an你指導我嗎?

回答

5

你必須標記你的類別ID參數爲[FromBody]:

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

默認情況下,簡單的類型,如字符串將模型從URI約束。