[英]How to response in right way from WebApi
I try to write api controller and I got some problem: no response after post message to WebApi. 我尝试编写api控制器,但遇到一些问题:向WebApi发布消息后无响应。 I try googling and I found a few answers, but it doesn't work for me.
我尝试使用Google搜索,但发现了一些答案,但对我来说不起作用。 I don't understand why.
我不明白为什么。
Code for http post request (from here , it's just example from simple mvc controller):
http 发布请求的代码(从这里开始 ,这只是简单的mvc控制器的示例):
public ActionResult Test()
{
RunAsync().Wait();
return null;
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:50984/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var gizmo = new ErrorModel
{
Key = "2ccab87f5f904d3688a28b1a1fb4269b",
Name = "HTTP Error 404"
};
HttpResponseMessage response = await client.PostAsJsonAsync("exceptionregistration/handle", gizmo);
if (response.IsSuccessStatusCode)
{
}
}
}
WebApi controller:
WebApi控制器:
public class HandleController : ApiController
{
[System.Web.Http.HttpPost, ValidateInput(false)]
public HttpResponseMessage Post([FromBody]ErrorModel errorData)
{
try
{
// some code
}
catch (Exception ex)
{
Logger.error(ex);
return null;
}
return Request.CreateResponse(HttpStatusCode.OK, "value");
}
}
And this line have never been executed completely ( no response ):
而且此行从未完全执行过( 无响应 ):
HttpResponseMessage response = await client.PostAsJsonAsync("exceptionregistration/handle", gizmo);
What's wrong? 怎么了? Why is no result when I wait a response?
为什么在我等待回复时没有结果?
Maybe is it a better way to post json message to web api controller? 也许这是将json消息发布到Web api控制器的更好方法吗?
I think you are running into a deadlock because of RunAsync().Wait();
我认为您由于
RunAsync().Wait();
陷入僵局RunAsync().Wait();
. 。 Your
Test()
Method is blocking the context thread, waiting for RunAsync()
to complete and RunAsync()
is waiting for the context to be free so it can complete. 您的
Test()
方法阻塞了上下文线程,等待RunAsync()
完成,而RunAsync()
等待上下文空闲以便它可以完成。 This blog from Stephen Cleary describes the problem in detail: link . Stephen Cleary的这篇博客详细描述了该问题: link 。
The solution would be changing the signature to allow "awaiting" on RunAsync()
: 解决方案是更改签名以允许在
RunAsync()
上“等待”:
public ActionResult Test()
to public async Task<ActionResult> Test()
public ActionResult Test()
到public async Task<ActionResult> Test()
and 和
RunAsync().Wait();
to await RunAsync();
await RunAsync();
您可以使用fiddler
来查找您的API是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.