Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

.net - Azure Functions call http post inside function

Is it possible to create HTTP(s) post request inside Azure Function? I am trying to create a custom webhook that is listening to one service and when triggered then its calling another service over HTTP using post.

My code looks like that:

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{

    BitbucketRequest data = await req.Content.ReadAsAsync<BitbucketRequest>();
    //DO STH WITH DATA TO GET e.g. USER STORY ID

    using(var client = new HttpClient()){
        client.BaseAddress = new Uri("https://SOME_TARGETPROCESS_URL/api/v1");
        var body = new { EntityState = new  { Id = 174 } };
        var result = await client.PostAsJsonAsync(
                       "/UserStories/7034/?resultFormat=json&access_token=MYACCESSTOKEN",
                       body);
        string resultContent = await result.Content.ReadAsStringAsync();
    }

    return req.CreateResponse<string>(HttpStatusCode.OK,"OKOK");
}

I suppose the problem is that currently HttpRequestMessage is occupying web socket and I can not create new Http Request.

Errors that I found in Exceptions details:

  • The underlying connection was closed: An unexpected error occurred on a send.
  • Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
  • Socket Exception Error Code : 10054
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For anyone else who lands here when searching for HttpClient in Azure functions.

https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections

// Create a single, static HttpClient
private static HttpClient httpClient = new HttpClient();

public static async Task Run(string input)
{
    var response = await httpClient.GetAsync("https://example.com");
    // Rest of function
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...