我在asp .net上设置了一个Web Api 2控制器来处理对localhost的简单发布请求,仅用于测试目的。当我使用“https://localhost:xxxx/api/test?content=teststring”时,控制器处理POST请求就好了,但是当使用“https://localhost:xxxx/api/test”作为带有teststring作为StringContent对象的uri时,我得到404错误。这是控制器代码:
[RoutePrefix("api")]
public class TestController : ApiController
{
[HttpPost]
[Route("test")]
public HttpResponseMessage PostTest(string content)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(content + "\nHiAndBye");
return response;
}
}
当我收到404错误时,以下是我发送POST请求的方式(来自控制台应用程序):
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://localhost:xxxxx");
StringContent content = new StringContent("teststring");
HttpResponseMessage response = httpClient.PostAsync("/api/test", content).Result;
如何解决404错误?
答案 0 :(得分:0)
如果Johnny在评论中的回答不够明确,您需要做的是将方法签名更改为
public HttpResponseMessage PostTest([FromBody] string content)
强制从请求正文而不是URL中读取content
参数。您可以在此处阅读更多内容https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
答案 1 :(得分:0)
我发现解决这个问题的方法是让PostTest控制器没有参数,并使用this.Request.Content.ReadAsStringAsync()。结果来获取请求的主体,所以控制器现在看起来像这样:
public HttpResponseMessage PostTest()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(this.Request.Content.ReadAsStringAsync().Result + "\nHiAndBye");
return response;
}