-1

Below is the code which works perfectly fine when i execute it on console application. The line
var postResponse = await client.SendAsync(req); give the result when i run the code in console app.

But when iam using this code in WebApi controller, this code halts on this line.

 using (var client = new HttpClient())
        {


            var auth = "MTAwNDgucnVsZXNlbmdpbmUuc2VydmljZTp2N3FuY3I4cWlz";
            client.BaseAddress = new Uri("https://federation-sts-stage.accenture.com");
            var req = new HttpRequestMessage(HttpMethod.Post, "https://federation-sts-stage.test.com/oauth/ls/connect/token");
            var cont = new FormUrlEncodedContent(bodyContents);
            cont.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            cont.Headers.ContentLength = Convert.ToInt64("125");
            req.Content = cont;
            req.Headers.Add("Authorization", "Basic " + auth);


            try
            {
                var postResponse = await client.SendAsync(req); // this is where the code keeps on waiting but works fine in console app
                postResponse.EnsureSuccessStatusCode();
                responseContents = postResponse.Content.ReadAsStringAsync().Result;


            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                return msg;
            }


            var responseObject = JObject.Parse(responseContents);
            return responseObject.Value<string>("access_token");
        }

I have also compared the request object in both the cases (in console app and in webapi controller call) but in both the cases the request object comes out same as below :

{Method: POST, RequestUri: 'https://federation-sts-stage.test.com/oauth/ls/connect/token', Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
  Authorization: Basic MTAwNDgucnVsZXNlbmdpbmUuc2VydmljZTp2N3FuY3I4cWlz
  Content-Type: application/json
  Content-Length: 125
}}

I dont know what iam doing incorrect.

As per the comments, i am putting the whole method which gets called from apicontroller as below, this method works fine from console app but when i call this method from apicontroller its kept on running.

public async Task<string> RequestTokenFromIssuer(string username, string password)
    {

        var bodyContents = new Dictionary<string, string>
        {
            { "grant_type", "client_credentials" },
            { "userName", username },
            { "password", password},
            { "scope", "read_rulesengine write_rulesengine" }
        };

        string responseContents = string.Empty;

        using (var client = new HttpClient())
        {


            var auth = "MTAwNDgucnVsZXNlbmdpbmUuc2VydmljZTp2N3FuY3I4cWlz";
            client.BaseAddress = new Uri("https://federation-sts-stage.test.com");
            var req = new HttpRequestMessage(HttpMethod.Post, "https://federation-sts-stage.test.com/oauth/ls/connect/token");
            var cont = new FormUrlEncodedContent(bodyContents);
            cont.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            cont.Headers.ContentLength = Convert.ToInt64("125");
            req.Content = cont;
            req.Headers.Add("Authorization", "Basic " + auth);


            try
            {
                var postResponse = await client.SendAsync(req);
                postResponse.EnsureSuccessStatusCode();
                responseContents = postResponse.Content.ReadAsStringAsync().Result;


            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                return msg;
            }


            var responseObject = JObject.Parse(responseContents);
            return responseObject.Value<string>("access_token");
        }

    }
Rpcoder
  • 271
  • 1
  • 3
  • 11
  • Could you please share you WebApi controller code? – Uriil Dec 04 '18 at 20:49
  • Is that your real auth key? – mjwills Dec 04 '18 at 20:49
  • Were you able to use Wireshark (or similar) to compare the data passing over the wire? Just to confirm the two are submitting the same https request? – mjwills Dec 04 '18 at 20:50
  • I have put up the whole method which iam calling from controller – Rpcoder Dec 04 '18 at 20:57
  • Please put a breakpoint on `var msg = ex.Message;` Does that breakpoint get hit? – mjwills Dec 04 '18 at 21:05
  • No the code doesn't hits there. – Rpcoder Dec 04 '18 at 21:10
  • 1
    Its not the cause of your issue, but you should know that using a `using` statement with HttpClient is a bad idea, see [here](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/). – maccettura Dec 04 '18 at 21:10
  • i don't know why downnvote, i have tried many things in order to fix this. – Rpcoder Dec 04 '18 at 21:11
  • maccettura - sorry, i don't agree as it disposes the instance of httpclient once its job is done. – Rpcoder Dec 04 '18 at 21:12
  • 3
    @Rpcoder Well thankfully you not agreeing with me is an opinion, not fact. [Even Microsoft's documentation](https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client) points out that you should be using a shared static instance. Relevant quote: `"HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors: 1. Creating a new HttpClient instance per request. 2.Server under heavy load."` – maccettura Dec 04 '18 at 21:15
  • How did you go with my Wireshark suggestion? Did you try the earlier Nick's suggestion of not using `.Result`? – mjwills Dec 04 '18 at 22:14
  • mjwills : well i did not tried that, thanks though. – Rpcoder Dec 07 '18 at 10:45
  • maccettura : well that's informative...i will try not to use HttpClient next time. – Rpcoder Dec 07 '18 at 10:46

1 Answers1

2

I believe your problem actually is on line

responseContents = postResponse.Content.ReadAsStringAsync().Result;

Never, ever to this in an async method. You should do it like:

responseContents = await postResponse.Content.ReadAsStringAsync();
Nick
  • 4,787
  • 2
  • 18
  • 24
  • the control doesn't reach to this line, as ive said, the code halts at : **var postResponse = await client.SendAsync(req);** and iam using await on it. – Rpcoder Dec 04 '18 at 21:01