我尝试使用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);
}
我做错了什么?感谢
答案 0 :(得分:0)
尝试为该控制器/方法添加路由,如下所示:
routes.MapRoute(
"yourRouteName", // Route name
"{controller}/{action}",
new { controller = "yourController", action = "TestUpload", uploaded="" } // Parameter defaults
);
答案 1 :(得分:0)
我想我明白了。 UploadString
上的WebClient
使用字符串参数作为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;
}