Returning Twiml through c# - twilio

Trying out something very basic in Twilio & C#. I am new to Twilio & I am not very strong with MVC
public class IncomingCallController : TwilioController
{
// GET: IncomingCall
[HttpGet]
public ActionResult Index()
{
var response = new VoiceResponse();
var dial = new Dial();
Response.ContentType = "text/xml";
response.Say("Please wait...transferring your call");
dial.Number("+919812345678");
return TwiML(response);
}
}
I need the above code snippet to return the static Twiml equivalent that I would have put in a Twiml bin.
I have configured the phone number to with a webhook url as
http://someaddress.azurewebsites.net/IncomingCall
Why am i getting an
11210-HTTP bad host name
error
I understand that I am doing something wrong here. I have tried using both a POST and GET request.
Can anyone who has knowledge of this point me in the right direction?
Where am I going wrong?
Any help would be appreciated.

Some issues are created by programmers who are in a tearing hurry....This was an issue created by yours truly..
Thanks to Phil's interaction I was able to find out...

Related

Read API Response Messages

I have Developed ASP.net Core Web API & Web APP Which are in the same solution but different projects.
in the API I have some validations/checking as you may call.
e.g: if user email already exists, the API returns 'Email alreday in use' like this
bool EmailExists = dbContext.Users.Any(u => u.Email == user.Email);
if (EmailExists)
{
return new JsonResult("Email Address already taken!, Try a differen Email");
}
and so on. in some cases I may need to check multiple columns one a time, (eg: UserName, Email, TellNum)
This is an example of calling the API in the MVC
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAPIUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.PostAsJsonAsync("Users", user);
if (Res.IsSuccessStatusCode)
{
//in here I want check the `Res` and if it contains the returned messages, I want to display them by assigning it to `TempData[infoMsg]`
// else some something(register user)
}
// Check the returned JsonResult messages here if statusCode is ultered eg: BadRequest
}
My Question is how can I display these types of response messages in razor view in the MVC(Web App). in PostMan its workin, returning the response messages in body.
I did a lot of research about this but couldn't come to conclusion. I also cantacted some Devs I know(not .NET) and they said use JavaScript to call your API, which means I have to change almost everything I have done so far.
I aslo tried ultereing the statuCode to something like BadRequest in the API(if Email exists) in which case it will be checked outside the if (Res.IsSuccessStatusCode) of the Httpclient.
any help or direction is highly appreciated.
You should return a http error and a body containing some data about it eg field and message to your mvc controller. That could be a 422 error or whatever you like really since it's effectively internal and just coming back to the mvc controller.
The controller can then add any such error to modelstate and you can use the razor model "client" validation mechanism to show the error associated with a field.
This is therefore using the same mechanism used for attribute validation in the controller where you'd do
if (!ModelState.IsValid)
This is air code but will hopefully give you the idea.
[HttpPost]
public ActionResult PostUpdate(User u)
{
// call service and await response
var response = await httpClient.PostAsJsonAsync(posturi, u);
var returnContent = await response.Content.ReadAsAsync<ReturnContent>();
if (response.Result != HttpStatusCode.OK)
{
ModelState.AddModelError(returnContent.FieldName,returnContent.Error);
return Page();
}
// etc
You will want a more sophisticated checking on errors of course and check you get the body you're expecting.
Maybe you just hard code the field and error message if there's only one possibility. Maybe work with an array of fields and errors if there could be numerous validation fails.

Accsing an API from console is working but same is not working with MVC web

I am trying to access BlockCypher from console Application which works absolutely fine. But when i am trying to access the same MVC Web Application, I am not getting the response from "BlockCypher". not sure why.
here is the link i am following:
BlockCypher git
here is the code i am using
Blockcypher objmain = new Blockcypher("XXXXXXXXXXXXXXX", Endpoint.BcyTest);
objmain.GenerateAddress().Wait();
please help, any idea what i am doing wrong in web.? or what i am missing.
You seem to be hitting a deadlock, instead of using Wait() in a synchronous context, instead make your action / parent code async and use await.
public async Task<ActionResult> MyAction()
{
var bc = new Blockcypher("..", Endpoint.BcyTest);
await bc.GenerateAddress();
// ..
}

MVC Request - Core .NET - Non HTML Response

I'm new to Core.NET and would greatly appreciate some enlightenment.
I've watched many PluralSight videos, and have Core .NET book 'Pro ASP.NET Core MVC'.
All very well cover Routing / Controller Initialization / Action Method Execution / Action Result / View Engine. I'm hung up on the Non HTML Response though. (Please see image below)
In Traditional ASP.NET if I wanted to call some class that did something and returned no value, I'd simply:
// Call Twilio class that sends a test message
TwilioRest Send_Test_SMS = new TwilioRest();
Send_Test_SMS.testSMS_Send();
My question is:
How do I call the above class's function from the controller.
When adding a controller or when modifying a controller for that - do I need to alter or add something to the Startup.cs file
The course materials I have do a great job at covering returning HTML views - such as:
//------book examples below-----
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
But I feel like an idiot trying to do something so simple and would appreciate some insight into this.
Thank you in advance.
So I'm not sure whether I got your point, but I guess you want to do sth like that:
//------book examples below-----
public IActionResult Index()
{
// Call Twilio class that sends a test message
TwilioRest Send_Test_SMS = new TwilioRest();
Send_Test_SMS.testSMS_Send();
return Ok(); // Similiar meaning as => return StatusCode(200);
}
It's up to your design / contract which status code you want to return here you can find a list of http codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
So to summarize you don't need to return 'HTML response', but obviously 'HTTP response' must be returned.
If I misunderstood you then apologize.

ASP.Net Web API: Regarding web api action calling url or end point url

i am new in asp.net web api. just reading a article on web api from this url http://www.c-sharpcorner.com/article/remote-bind-kendo-grid-using-angular-js-and-Asp-Net-web-api/
now see this code
[RoutePrefix("api/EmployeeList")]
public class EmployeeDetailsController : ApiController
{
[HttpGet]
[Route("List")]
public HttpResponseMessage EmployeeList()
{
try
{
List<Employee> _emp = new List<Employee>();
_emp.Add(new Employee(1, "Bobb", "Ross"));
_emp.Add(new Employee(2, "Pradeep", "Raj"));
_emp.Add(new Employee(3, "Arun", "Kumar"));
return Request.CreateResponse(HttpStatusCode.OK, _emp, Configuration.Formatters.JsonFormatter);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.OK, ex.Message, Configuration.Formatters.JsonFormatter);
}
}
}
as per my understanding the requesting url should be /api/EmployeeList/List but if anyone look the above image then must notice different url api/Employee/GetEmployeeList is being used to call list action method. so i just like to know the reason why different url is getting issued to call List action function ?
also do not understand how this url api/Employee/GetEmployeeList can work in this situation because controller name is EmployeeDetailsController but RoutePrefix has been used to address it api/EmployeeList and action method name is EmployeeList() which has been change to List..........so some one tell me how this url api/Employee/GetEmployeeList can invoke list action of web api ?
please discuss in detail. thanks
Did you activate AttributeRouting? If not, standard routing is in place and your current attributes will be ignored.
You need to do this in the WebApi registration process, like this:
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
Then, you can remove any method call like this:
config.Routes.MapHttpRoute
to disable conventional routing.
BTW, the call api/Employee/GetEmployeeList is valid because Employee is the name of your controller, Get is the verb and EmployeeList is the name of the method.
Did you enable attribute routing? You do this by default in webapiconfig.cs by adding this line of code:
config.MapHttpAttributeRoutes();
#Monojit-Sarkar. The URL the user showed in postman did not also match the code. In the code, these are the users we expect to see:
_emp.Add(new Employee(1, "Bobb", "Ross"));
_emp.Add(new Employee(2, "Pradeep", "Raj"));
_emp.Add(new Employee(3, "Arun", "Kumar"));
But the results in postman are different as shown in the image the user posted. So something is disconnected from the article/image and the sample code.

.net MVC Odata endpoint works on POST, but 404s on GET

My question should have a simple answer, but after hours of experimentation and googling, I have nothing so now I'm here.
I am working with .net MVC 5 odata 2.0. I am trying to create a new odata endpoint that works on a get. I've successfully created a few endpoints that work with POST, but I can't seem to get one that works as a GET.
relevant code
WebApiConfig.cs
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Review>("Reviews");
builder.EntitySet<Strategy>("Strategies");
ActionConfiguration ReviewsInStrategy = builder.Entity<Strategy>().Action("ReviewsInStrategy");
ReviewsInStrategy.ReturnsCollectionFromEntitySet<Review>("Reviews");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
StrategiesController.cs
[EnableQuery]
public IQueryable<Review> ReviewsInStrategy([FromODataUri] Guid key){
Strategy strategy = db.Strategies.Find(key);
return strategy.Reviews
}
Now I go to fiddler and try a GET to
[myurl]/odata/Strategies(guid'[myguid]')/ReviewsInStrategy
I get a 404 result. But when I change fiddler to a POST (no other change - I don't add accept headers or content types or anything) it works just fine.
How do I make this work with GET?
You need to add a Get-function to your controller:
[EnableQuery]
public SingleResult<Strategies> Get([FromODataUri] Guid key)
{
IQueryable<Strategies> result = db.Strategies.Where(p => p.Id == key);
return SingleResult.Create(result);
}
That way you can use a GET request on the Strategies-resource. If you still want to use a custom action you must add the parameter to your config:
ActionConfiguration ReviewsInStrategy = builder.Entity<Strategy>().Action("ReviewsInStrategy").Returns<Review>().Parameter<Guid>("Key");
[HttpGet]
[ODataRoute("ReviewsInStrategy(Key={key})")]
public IHttpActionResult<Review> ReviewsInStrategy([FromODataUri] Guid key){
Strategy strategy = db.Strategies.Find(key);
return Ok(strategy.Reviews);
}
Not sure if all this works with the complex type Guid. Maybe you need to change it to string and parse it inside the function. Here is a good msdn article about this.

Resources