我在尝试用WebClient调用的web服务上有两个方法:
[Route("TestDownload")]
[HttpGet]
public string TestDownload()
{
return "downloaded";
}
[Route("TestUpload")]
[HttpPost]
public string TestUpload(string uploaded)
{
return uploaded;
}下面的代码可以工作:
using (var wc = new WebClient())
{
var sResult = wc.DownloadString("http://localhost/Website/TestDownload");
Console.WriteLine(sResult);
}此代码抛出System.Net.WebException:(404) Not Found
using (var wc = new WebClient())
{
var sResult = wc.UploadString("http://localhost/Website/TestUpload", "test");
Console.WriteLine(sResult);
}我做错了什么?谢谢
发布于 2017-06-03 01:25:24
我想我想通了。WebClient上的UploadString使用字符串参数作为http请求正文。默认情况下,WebApi从查询字符串(参见https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api)为简单类型(包括字符串)提供控制器方法参数。要覆盖此行为并指示将在请求正文中找到字符串参数,可以使用[FromBody]属性。
[Route("TestUpload")]
[HttpPost]
public string TestUpload([FromBody] string uploaded)
{
return uploaded;
}发布于 2017-02-28 10:38:38
尝试为该控制器/方法添加路由,如下所示:
routes.MapRoute(
"yourRouteName", // Route name
"{controller}/{action}",
new { controller = "yourController", action = "TestUpload", uploaded="" } // Parameter defaults
);https://stackoverflow.com/questions/42496641
复制相似问题