简体   繁体   中英

Calling WCF REST Service from ASP.Net does not return

I have a WCF service implemented as windows service and I need to call this service from a ASP.Net application. The WCF service responds using a custom formatter.

I have tested the code below and it works if I run it from a console application or even from a unit testing project but it hangs if I call it from an ASP.Net application.

I have been able to debug the request in the WCF code and I see it responds, but the client does not receive the response.

Does anyone know any limitation that can impede the response to reach the ASP.NET client application?

public async Task<SomeDataToken> PostData()
{
    const string SomeMediaTypeName = "application/some-media-type";
    SomeDataToken request = new SomeDataToken();           

    using (var client = new HttpClient())
    {
        var formatter = new SomeMedyaTypeFormatter();
        client.BaseAddress = new Uri(@"http://localhost:8001/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(SomeMediaTypeName));
        client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", SomeMediaTypeName);

        try
        {
            var httpResponse = await client.PostAsync("SomeController/SomeAction", request, formatter);
            var result = await httpResponse.Content.ReadAsAsync<SomeDataToken>(new[] { formatter });
            return result;
        }
        catch
        {
            return null;
        }

    }
}

It seems the problem is not related to WCF but to the way ASP.Net / MVC manages async, as it creates its own threads.

When making async calls from any sincrhonous part of an ASP.NET / MVC application, pay attention to add .ConfigureAwait(false) to the PostAsync or GetAsync methods. Otherwise, the PostAsync or GetAsync call will hang.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM