Dha*_*nki 1 using http-post 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);
}
Run Code Online (Sandbox Code Playgroud)
// 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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我在Northwind数据库中发布代表"类别"表的custome对象时所有工作正常但我无法发布标量数据,如整数和字符串
当我发布字符串数据类型时,我得到以下异常
{"消息":"未找到与请求URI匹配的HTTP资源' http:// localhost:49931/api/Supplier/RemoveCategory /'.","MessageDetail ":"未在控制器'供应商'上找到任何操作与请求匹配."}
谁能指导我?
您必须将CategoryID参数标记为[FromBody]:
[HttpPost]
public HttpResponseMessage RemoveCategory([FromBody] string CategoryID)
{ ... }
Run Code Online (Sandbox Code Playgroud)
默认情况下,简单类型(如string)将从URI绑定模型.
| 归档时间: |
|
| 查看次数: |
2958 次 |
| 最近记录: |