I'm writing an IVR application using Twilio in .net MVC.Here is my code
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/VoiceMain/ReceiveCall")]
public HttpResponseMessage ReceiveCall()
{
var response = new VoiceResponse();
response.Say("Welcome, How can I help you?", voice: "alice", language: "en-AU");
var gather = new Gather(
input: new[] { Gather.InputEnum.Speech }.ToList(),
action: new Uri("/api/Voice/ProcessCall?ConversationId=0"), method: Twilio.Http.HttpMethod.Post, language: "en-AU", timeout: 3);
response.Append(gather);
var res = Request.CreateResponse(HttpStatusCode.OK);
res.Content = new StringContent(response.ToString(), Encoding.UTF8, "text/xml");
return res;
}
And here is my ProcessCall method
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/Voice/ProcessCall")]
public HttpResponseMessage ProcessCall(VoiceRequest request,int ConversationId=0)
{
string inputQuery;
inputQuery = request.SpeechResult;
}
I am sending SpeechResult text to dialogflow for further processing.
In twilio webhook when i use ngrok url like below whole process goes smooth
I hosted this api on azure, so instead of ngrok url when i use azure url as webhook in twilio like below
twilio is giving error..
Can someone help me in this as I am new in twilio..Thanks
Related
I'm writing a simple dotnet core API, under search controller which like below :
[HttpGet("order")]
public async Task <Order> SearchOrder(string ordername, int siteid) {
return await service.getorder(ordername,siteid)
}
The swagger UI where the path https://devehost/search/order test pretty work, but when I use another client to call this api by below
client = new HttpClient {
BaseAddress = new Uri("https://devehost")
};
var request = new HttpRequestMessage(HttpMethod.Get, "Search/order") {
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>> {
new("ordername", "pizza-1"),
new("siteid", "1"),
})
};
var response = await client.SendAsync(request);
The status code always return bad request. But the postman is work, can I know the problem inside?
Thank you
For a GET request, the parameters should be sent in the querystring, not the request body.
GET - HTTP | MDN
Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.
For .NET Core, you can use the Microsoft.AspNetCore.WebUtilities.QueryHelpers class to append the parameters to the URL:
Dictionary<string, string> parameters = new()
{
["ordername"] = "pizza-1",
["siteid"] = "1",
};
string url = QueryHelpers.AppendQueryString("Search/order", parameters);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await client.SendAsync(request);
I try to send request with serialized data to my server using HttpClient
var content = JsonConvert.SerializeObject(note);
var response = await _client.PostAsync(url, new StringContent(content));
here my method in controller:
[HttpPost]
public ActionResult<Note>Create([FromBody]note)
{
_noteService.Create(note);
return new Note();//CreatedAtRoute("GetBook", new { id = note.Id.ToString() }, note);
}
and i get error Unsupported MediaType, i tried to change parameter "note" datatype to StringContent and i get "Bad Gateway" error, i tried to change it to String data type and it is empty.
How i can get data sending from xamarin application on my server ?
Edited:
Probably i have to get serialized string and deserialize it to my object.
Solved, please check solution below
Xamarin Code:
var content = JsonConvert.SerializeObject(note);
var response = await _client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json"));
.Net Core WebApi Code:
[HttpPost]
public ActionResult<Note>Create(Note note)
{
_noteService.Create(note);
return CreatedAtRoute("GetNote", new { id = note.Id.ToString() }, note);
}
I am creating prototype of application where in I am trying to send data in request header and body from C# MVC Controller and also created web api project Post action to process the request.
My code goes like this::
MVC Project code to Post Request:
public class HomeController : Controller
{
public async Task<ActionResult> Index()
{
VM VM = new VM();
VM.Name = " TEST Name";
VM.Address = " TEST Address ";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:58297");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("username","test");
var json = JsonConvert.SerializeObject(VM);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var result1 = await client.PostAsync("api/Values/Post", content);
}
return View();
}
}
My code in WEB API project :
// POST api/values
public IHttpActionResult Post([FromBody]API.VM vm)
{
try
{
HttpRequestMessage re = new HttpRequestMessage();
StreamWriter sw = new StreamWriter(#"E:\Apple\txt.log", false);
var headers = re.Headers;
string token = "";
if (headers.Contains("username"))
{
token = headers.GetValues("username").First();
}
sw.WriteLine("From header" + token);
sw.WriteLine("From BODY" + vm.Name);
sw.WriteLine("From BODY" + vm.Address);
sw.WriteLine("Line2");
sw.Close();
return Ok("Success");
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
What I have understood is [FromBody]API.VM vm gets data from Http request body which means vm object is getting data from HTTP Request body.I am able to get request body. I am not able to understand how do I pass data in header from MVC controller (I want to pass JSON Data) and retrieve data in WEB Api post method?
I have used client.DefaultRequestHeaders.Add("username","test"); in MVC project to pass header data and
HttpRequestMessage re = new HttpRequestMessage();
var headers = re.Headers;
string token = "";
if (headers.Contains("username"))
{
token = headers.GetValues("username").First();
}
in WEB API project to get data but I am not able to get username value.
In order to get your data via headers, you would need to enable CORS: Install-Package Microsoft.AspNet.WebApi.Cors in your project and then in your Register method under WebApiConfig.cs, add this line: EnableCors();.
Once done, you can access your header variable as:
IEnumerable<string> values = new List<string>();
actionContext.Request.Headers.TryGetValues("username", out values);
You can get all headers being passed to a method of a web API using below lines inside that web API method:
HttpActionContext actionContext = this.ActionContext;
var headers = actionContext.Request.Headers;
I am developing a web application using C# that uses 2 factor authentication during Sign Up. I have already tried 2FA using Nexmo's API. It worked fine. All I had to do was call their API and speciy the 'to' number. Here is the code:
public ActionResult Start(string to)
{
var start = NumberVerify.Verify(new NumberVerify.VerifyRequest
{
number = to,
brand = "NexmoQS"
});
Session["requestID"] = start.request_id;
return View();
}
Now, I decided to give Twilio a try. I came across Authy and it's process. I found their 2FA API here. But I don't understand where should I enter the 'to' number as specified in Nexmo. I am a beginner and using .NET(C#) code snippet. Here is the code snippet. Please help me configure this code as I am able to do in Nexmo.
public static async Task VerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
// https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE
HttpResponseMessage response = await client.GetAsync("https://api.authy.com/protected/json/phones/verification/check?phone_number=5558675309&country_code=1&verification_code=3043");
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
}
They have given a cURL implementation of their api here, please help me configure it in C#.
curl "http://api.authy.com/protected/json/users/new?api_key=d57d919d11e6b221c9bf6f7c882028f9" \
-d user[email]="user#domain.com" \
-d user[cellphone]="317-338-9302" \
-d user[country_code]="54"
Twilio developer evangelist here.
When making a call to the API, you do need to add the X-Authy-API-Key header as well as a URL parameter api_key. Also, to start the process of verifying a number you should be making a POST request with the data you need to send to the API.
The two bits of data that you need are the phone number and the country code for that phone number. Though you can set some other values, like the way you want to send the verification code (via sms or call).
I would update your code to look like this:
public static async Task StartVerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
var AuthyAPIKey = 'YOUR AUTHY API KEY';
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
var values = new Dictionary<string, string>
{
{ "phone_number", "PHONE NUMBER TO VERIFY" },
{ "country_code", "COUNTRY CODE FOR PHONE NUMBER" }
};
var content = new FormUrlEncodedContent(values);
var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}";
HttpResponseMessage response = await client.PostAsync(url, content);
// do something with the response
}
Then when the user enters the code, you need to check it. Again you should add the API key as a header and send as a URL parameter too, along with the phone number, country code and the verification code the user entered, this time as a GET request.
public static async Task CheckVerifyPhoneAsync()
{
// Create client
var client = new HttpClient();
var AuthyAPIKey = 'YOUR AUTHY API KEY';
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);
var phone_number = "PHONE NUMBER TO VERIFY";
var country_code = "COUNTRY CODE FOR PHONE NUMBER";
var verification_code = "THE CODE ENTERED BY THE USER";
var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}&phone_number={phone_number}&country_code={country_code}&verification_code={verification_code}";
HttpResponseMessage response = await client.GetAsync(url);
// do something with the response
}
Let me know if that helps at all.
I have fetch channel history in my .Net Web API.
The slack reference https://api.slack.com/methods/channels.history it states that we need to post the request.
Please if someone could help me with the code.
Part of Code I have implemented:
#region create json payload to send to slack
GetLatestMessage payload = new GetLatestMessage()
{
channel = "###",//value.channel_name,
token = "############################"//added the token i have generated
// user_name = value.user_name,
//text = value.text
};
#endregion
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}
I figured out the issue I was facing.I was trying to sent the post json data in to Slack url. However The Slack Web API doesn't accept JSON data.Now when I post data using standard HTTP form attributes it accepts and returns proper response.
New code:
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", new NameValueCollection() {
{"token","###################"},
{"channel","######"}});
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}