Hane
Hane

Reputation: 11

write a http post request to bot framework running on localhost

I have a bot running on http://localhost:3978/api/messages. Instead of debugging it using an emulator, can I go about using a http post request to the messaging endpoint of the bot? If so, how do I go about doing it?

I am using c# microsoft bot framework, and I am new to this application. I do not want to use any channels or DirectLine api, just using Httpclient.

Upvotes: 1

Views: 2607

Answers (2)

D4RKCIDE
D4RKCIDE

Reputation: 3426

You can do this with C# using code similar to below. Note that you would have to construct an Activity to send by setting the appropriate properties for your needs, which is not included in this code.

//make a call to get an auth token
string token;
using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["grant_type"] = "client_credentials";
    values["client_id"] = "YOUR APP ID";
    values["client_secret"] = "NcOXRwb51joibEfzUuNE04u";
    values["scope"] = "YOUR APP ID/.default";

    var response =
        client.UploadValues("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", values);

    var responseString = Encoding.Default.GetString(response);
    var result = JsonConvert.DeserializeObject<ResponseObject>(responseString);
    token = result.access_token;
}

//you will need to adjust this value for your project.
//this example for a proxy project so the service url here is
//just an arbitrary endpoint I was using to send activities to
activity.ServiceUrl = "http://localhost:4643/api/return";    

var jsonActivityAltered = JsonConvert.SerializeObject(activity);

using (var client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/json");
    client.Headers.Add("Authorization", $"Bearer {token}");

    try
    {
        var btmResponse = client.UploadString("http://localhost:3971/api/messages", jsonActivityAltered);
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

Upvotes: 2

Imsopov
Imsopov

Reputation: 155

Have you tried using something like postman? (it's free and easy to use)

https://www.getpostman.com/

You can also write scripts in postman

otherwise you can just go to the endpoint of your API in the browser

http://localhost:3978/api/

I see you mentioned you wanted to make a console application.

You could do that. I'd suggest using postman though.

Here is an example of sending a file as well as some querystring data and Authentication using a Bearer token.

Sorry it may not be exact. Had to do a bit of copy pasting/deleting from some code examples if have

        using (HttpClient client = new HttpClient())
        {
            JObject jsonModel = new JObject();
            client.BaseAddress = new Uri("http://localhost:3978/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);

                using (var multipartFormDataContent = new MultipartFormDataContent())
                {
                    var values = new[]
                    {
                        new KeyValuePair<string, string>("firstname", lastname),
                        new KeyValuePair<string, string>("lastname", lastname),
                        new KeyValuePair<string, string>("payloadFile", FileName)
                    };

                    foreach (var keyValuePair in values)
                    {
                        multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                        String.Format("\"{0}\"", keyValuePair.Key));
                    }

                    ByteArrayContent fileContent = new ByteArrayContent(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));
                    string FullxmlString = File.ReadAllText(Path.Combine(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));


                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("payloadFile") { FileName = "payloadFile" };
                    multipartFormDataContent.Add(fileContent);

                    HttpResponseMessage response = client.PostAsync("api/message", multipartFormDataContent).Result;
                    string returnString = response.Content.ToString();

                    using (HttpContent content = response.Content)
                    {
                        string res = "";
                        Task<string> result = content.ReadAsStringAsync();
                        res = result.Result;
                    }
                }
       }

Upvotes: -1

Related Questions