1

I am having an Http triggered azure function which I am able to debug successfully using Postman by calling the api in postman and getting the desired response. Now I am trying to debug by calling the api from a separate method and that I am doing by calling the api in the main function something like this: Azure Function:

 public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            

            log.LogInformation("C# HTTP trigger function processed a request.");

            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            return new OkObjectResult("Test");

        }
    }
 class Program
        {
             static async Task Main(string[] args)
        {
            HttpClient client = new HttpClient();
            var requestUri = new Uri("http://localhost:7071/api/Function1");
            var rec = "Test:test";
            var response = await client.PostAsJsonAsync(requestUri, rec);
        }}

When I run I get an error in the last line saying "target machine actively refused the connection". The url is same which I am passing in postman and when I do from postman, it hits my function method. What wrong am I doing here??

Note: I have not yet published my function as I am debugging locally now

Ankit Kumar
  • 476
  • 1
  • 11
  • 38
  • Offtopic: You should be using `async` methods. You should never make a blocking call to `.Result`. – Dai Jan 23 '21 at 15:02
  • How are you running the Azure Function locally? Are you absolutely certain that your another process on your same machine is listening to `http://localhost:7221` and that it isn't `https:` and a different port number? You *do* know how `localhost` connections work, right? – Dai Jan 23 '21 at 15:04
  • Also, if this is a UWP application you're building are you aware that `localhost` client connections are blocked by default on Windows? – Dai Jan 23 '21 at 15:04
  • "I removed async as this is my main method and it wont allow async method" - but **`Main` can be `async`!** - where are you getting that incorrect information from? – Dai Jan 23 '21 at 15:04
  • when I did , async I got the error as main method cant be async, and so i removed the async part.. the url is same which gets generated when i build my function locally, thats how you use the url in postman to debug – Ankit Kumar Jan 23 '21 at 15:06
  • What error did you get? You won't get any errors unless you're using an old version of C#. C# added support for `async Task Main(String[] args)` back in C# 7.1 back in VS2017. `async void` won't work, you need to use `async Task`. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.1/async-main – Dai Jan 23 '21 at 15:08
  • "the url is same which gets generated when i build my function locally" - yes, but is it **actually running**? Do you see any console window pop-up? – Dai Jan 23 '21 at 15:09
  • yes console windows pop up but then I receive the error as target machine actively refused the connection.. I fixed the async part – Ankit Kumar Jan 23 '21 at 15:10
  • maybe if you have same scenario where you have an api which you can call from postman, you can suggest how to call it in from a separate method. – Ankit Kumar Jan 23 '21 at 15:13
  • Can you put the screenshot of successful request and response payload along with url and headers? – user1672994 Jan 23 '21 at 15:14
  • My only real suggestion is to fire-up Wireshark with Loopback enabled and spot the difference between Postman vs. your own C# client. See here: https://wiki.wireshark.org/CaptureSetup/Loopback – Dai Jan 23 '21 at 15:14
  • I am editing and posting my azure function http trigger method, response in Postman , i get is "Test" – Ankit Kumar Jan 23 '21 at 15:15
  • 1
    On a side note, should `var rec = "Test:test";` this be defined as `var rec = new { Test = "test" };` to represent as an object? – user1672994 Jan 23 '21 at 15:28
  • @AnkitKumar - Also you method exposed over both get and post. so what happens if you make a HttpGet request from your program? – user1672994 Jan 23 '21 at 15:30
  • same error with GetAsync as well – Ankit Kumar Jan 23 '21 at 15:53
  • it will be helpful if someone has tried triggering this azure function from client side and can provide the way to do it. i think i am doing right when I run it in cloud but i would like to debug the response. – Ankit Kumar Jan 23 '21 at 16:00
  • Check [this](https://stackoverflow.com/questions/42482223/azure-functions-call-http-post-inside-function). on internet, you can find various solutions/setup like yours. I've developed various azure functions and consume using HttpClient and never got the problem you have mentioned. – user1672994 Jan 23 '21 at 17:07
  • What happens if you call the same Get URL from browser? does it hit? – user1672994 Jan 23 '21 at 17:08
  • Hi, any update? – Cindy Pau Jan 25 '21 at 07:56

1 Answers1

1

When I run I get an error in the last line saying "target machine actively refused the connection". The url is same which I am passing in postman and when I do from postman, it hits my function method. What wrong am I doing here??

First of all, please make sure your function runtime is still running.

And below code works fine on my side:

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            HttpClient client = new HttpClient();
            var requestUri = new Uri("http://localhost:7071/api/Function1");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
            request.Method = "POST";
            string contents = "{\"Test\":\"test\"}";

            byte[] content = Encoding.UTF8.GetBytes(contents);
            int contentlength = content.Length;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(content, 0, (int)contentlength);
            }
            using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
            {
                StreamReader reader = new StreamReader(resp.GetResponseStream());
                string text = reader.ReadToEnd();
                Console.WriteLine(text);
            }
        }
    }
}
Cindy Pau
  • 13,085
  • 1
  • 15
  • 27