Delete email using mailinator API - c#

I am creating application to access public emails in mailinator. I can view emails but I have difficulties when I am trying to delete them.
https://mailinator.com/apidocs.jsp all examples from documentacion worked except this one.
I have code to POST Http request:
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "msgid", id}
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.mailinator.com/api/delete?", content);
var responseString = await response.Content.ReadAsStringAsync();
}
Only error it throws is (405) Method Not Allowed. or Method is not supported by this URL.
So I guess either my url that I'm sending is bad, either my code.
I need some help to figure it out.

According to the API docs you need to pass a valid token with every call. The delete API example looks like this:
curl "https://api.mailinator.com/api/delete?id=1373143878-0-test22&token=..."
The elipsis (...) there needs to be a valid token. So, add the token to your values dictionary.

Related

How to replicate Postman POST request in C#

I'm fairly new to .NET's HTTPClient class, hence kindly excuse if I sounded noob. I'm tryin to replicate Postman's POST request in C# .Net and written following code. However I'm not getting any response but StatusCode: 404. Could someone assist understanding where I'm going wrong?
Also I'd like to understand, how do set Body in following code.
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://testURL.com"),
Timeout = TimeSpan.FromMinutes(10)
};
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/wav"));
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic ldjfdljfdlfjdsjfdsl");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("model", "Test"),
});
var result = httpClient.PostAsync("api/v1/recognize", content).Result;
Here is what I'm doing in Postman and it works:
"Params" in Postman refers to query parameters which are appended to the URL. You'll see that the URL in Postman contains the parameters you added in the "Params" tab:
However, it seems those are just dummy values you've entered so perhaps you don't need them? In any case, the way you add query parameters to the request for HttpClient is a little different as it needs to be added to the URL.
After that you also need to add the audio file as content to your request. At the moment you're setting the "Accept" header to "audio/wav" but you probably want to set the "Content-Type" header instead (or are you expecting a WAV file to be returned in the response too?).
As far as I can see this is what you're missing:
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMinutes(10);
// Set request headers
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic ldjfdljfdlfjdsjfdsl");
// Set query parameters
var uriBuilder = new UriBuilder("https://testURL.com/api/v1/recognize");
uriBuilder.Query = "model=Test";
// Build request body
// Read bytes from the file being uploaded
var fileBytes = File.ReadAllBytes(wavFilePath);
// Create request content with metadata/headers to tell the
// backend which type of data (media type) is being uploaded
var byteArrayContent = new ByteArrayContent(fileBytes);
byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("audio/wav");
// Wrap/encode the content as "multipart/form-data"
// See example of how the output/request looks here:
// https://dotnetfiddle.net/qDMwFh
var requestContent = new MultipartFormDataContent
{
{byteArrayContent, "audio", "filename.wav"}
};
var response = await httpClient.PostAsync(uriBuilder.Uri, requestContent);
}
I haven't tested this of course against your application, but it should be something along the lines of this. It might be that the backend doesn't expect "multipart/form-data" and just needs the "audio/wav". I can't see the output headers in your Postman screenshots, but if so, you can use byteArrayContent directly instead of wrapping it in MultipartFormDataContent.
Note: Don't use httpClient.PostAsync(...).Result. If you want to use the asynchronous method, you should await it. Depending on your code, using Result might give you problems if you're not careful. And remember to dispose the HttpClient after use (easiest solution is to use a using statement). If you plan on reusing the HttpClient for more requests, you can avoid disposing it until you're done.

"Pass through" controller action (gets and returns JSON) in .NET Core 3.1

Someone's probably done this before but I can't seem to formulate the question properly to find results. I want to make AJAX calls from a view, but I can't directly call the external API from javascript because there's a key that I can't expose. My idea is to have another controller action that I call from the page that calls the actual external REST API I want to get data from and just passes it on as a JSON. I see lots of examples of getting a JSON through C# and deserializing it but not many where you get a JSON and then return it and consume it from the view. Any help appreciated.
public JsonResult GetStuff()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("Stuff/?Id=" + id).Result;
*code to take response and pass it on as a JSON that I can consume from Javascript
}
Here is what I recommend.
[HttpGet("myapi/{id}");
public async Task MyApi(int id) {
// Replace these lines as needed to make your API call properly.
using HttpClient client = new() {
BaseAddress = REMOTE_SERVER_BASE
}
// Make sure to properly encode url parameters if needed
using HttpResponseMessage response = await client.GetAsync($"myapi/{id}");
this.HttpContext.Response.StatusCode = (int)response.StatusCode;
foreach (KeyValuePair<string, IEnumerable<string>> header in response.Headers) {
this.HttpContext.Response.Headers[header.Key] = new StringValues(header.Value.ToArray());
}
await response.Content.CopyToAsync(this.HttpContext.Response.Body);
}
This will copy all the common response fields such as status code, headers, and body content, over to your response.
This code isn't tested so you might have to tweak it a bit but it should be enough to get you started.

Twilio Authy 2FA for OneCode C# Implementation

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.

Retrieve list object from HttpClient call to web api

I am trying to retrieve a list object from Web api via code behind. I have the following code:
var update = new Update();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:xxxxx/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("yada yada yada");
var result = response.Content.ReadAsStringAsync();
Where I'm getting confused is how to handle the data coming in so that it is in List<> format. I want to be able to enumerate through the List so I can manipulate the individual updates. When I hit the service with Fiddler, I get either a json or xml array depending on what I set the content-type to, so it works at that point. I just need some help figuring out some content negotiation. Any help is appreciated.

How to write nested Json web services in c# for windows store app

I'm working on windows store app where i am using a web service which have parameter which are nested like this
userData, #"user_login",
email, #"email",password, #"password",
user_login key contains to key email and password with their value .I Hit the web service in the fiddler and if works i am getting the response the parameter string i used
{
"user_login":{"email" : "mmmmmmmm#fdhfgh.co","password" : "pass1234"}
}
when i am using this parameter string in my code i am getting error of status code 400 bad request due to the parameter string .
here is my code
string content = string.Empty;
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Date = DateTime.Now;
var httpContent = new System.Net.Http.StringContent("{'user_login':[{'email':"mmmmmmmm#fdhfgh.co",'password':'pass1234'}}]", Encoding.UTF8,"application/json");
var httpResponse = await httpClient.PostAsync(" http://localhost/appi/pupil/log_in", httpContent);
content = await httpResponse.Content.ReadAsStringAsync();
help me out with your valuable suggestions.
In your C# code, you're passing in an array (as denoted by the [ ]'s). It doesn't look like your were doing that in Fiddler. It also looks like the [ ]'s aren't formatted properly. I'd try just taking that out.
EDIT:
"{\"user_login\":{\"email\":\"mmmmmmmm#fdhfgh.com\",\"password\":\"pass1234\"}}"
If this is the correct signature, the above JSON would work.
EDIT 2:
var httpResponse = await httpClient.PostAsync(" http://localhost/appi/pupil/log_in", httpContent);
Couldn't help but notice that you had "localhost/appi" instead of "localhost/api". That could possibly be a typo? Along with that leading space.

Categories