Thursday, March 15, 2018

Post to Microsoft Teams webhook with .net

This took me way too long to try and find out how to do.   Setting up the teams web hook is simple and straightforward and there are plenty of resources on where to find instructions but what took some time was posting to that web hook with .net code.

There is a simple example using Powershell but no way to show how that translates to .net



$url = "https://outlook.office.com/webhook/{yourwebhookhere}
$body =  ConvertTo-JSON @{text = "Gonzo, also known as the great!"}
Invoke-RestMethod -uri $uri -Method Post -body $body -ContentType 'application/json'

That is pretty easy but how about in .net?
The trick is using an HTTP client the only post method is postAsync so you need to either have an Async method or do this trick, this is because nothing will happen if you do not have async methods all the way up the stack.

vb.net
Private Function postToWebHook as string
        Dim _uristring As String = "https://outlook.office.com/webhook/{yourwebhookhere}"
        Dim jstring As String = "{""text"":  ""I just said something!""}"
        Dim pload As Payload = New Payload With {.title = "title", .text = "I just created a new            header!"}
        Dim payloadJson As String = JsonConvert.SerializeObject(pload)
        Dim content = New StringContent(payloadJson)
        content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/json")
        Dim client As New HttpClient
        Dim uri = New Uri(_uristring)
        Dim task As Task(Of HttpResponseMessage) = client.PostAsync(uri, content)
     
       return task.Result.ToString
end function