HttpClient を使用して ASP .Net Web API を呼び出し、アクションを正常に呼び出しています。また、カスタム オブジェクトをアクションに POST することもできます。
今私が直面している問題は、整数、文字列などのスカラーデータ型を投稿できないことです...
以下は、アクションを呼び出すコントローラーとアプリケーション コードです。
// 呼び出すテスト アプリケーション
[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 データベースの「Category」テーブルを表すカスタム オブジェクトを投稿すると、すべてが正常に機能しますが、Integer や String などのスカラー データを投稿できません。
文字列データ型を投稿すると、次の例外が発生します
{"メッセージ":"要求 URI に一致する HTTP リソースが見つかりませんでした ' http://localhost:49931/api/Supplier/RemoveCategory/ '.","MessageDetail":"コントローラ 'Supplier' でアクションが見つかりませんでしたリクエストに一致します。"}
誰でも私を案内できますか?