Pergunta

I try to write api controller and I got some problem: no response after post message to WebApi. I try googling and I found a few answers, but it doesn't work for me. I don't understand why.

Code for http post request (from here, it's just example from simple mvc controller):

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:

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?

Foi útil?

Solução

I think you are running into a deadlock because of 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. This blog from Stephen Cleary describes the problem in detail: link.

The solution would be changing the signature to allow "awaiting" on RunAsync():

public ActionResult Test() to public async Task<ActionResult> Test()

and

RunAsync().Wait(); to await RunAsync();

Outras dicas

you can use fiddler to find out whether your API works or not.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top