I want to POST a file to an API by RestSharp, but the Method.Post encounter error as cannot convert from 'RestSharp.Method' to 'string?', and the error for the Method.POST is 'Method' does not contain a definition for 'POST'?
using RestSharp;
using System;
using System.Net;
using System.Net.Http;
namespace UploadToAzure
{
class Program
{
static void Main()
{
var client = new RestClient("http://localhost:7071/api/Function1");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("File", "/D:/sample Files/audio0001.mp3");
IRestResponse response = (IRestResponse)client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
Thanks for your answers!
It solved when I add string of destination to RestRequest and change IRestResponse to RestResponse. In addition correct the path of file.
using RestSharp;
using System;
using System.Net;
using System.Net.Http;
namespace UploadToAzure
{
class Program
{
static void Main()
{
var client = new RestClient("http://localhost:7071/api/Function1");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("File", #"D:/sample Files/audio0001.mp3");
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
I had similar issue, but solved it by doing the following two things
Changed POST to Post.
Putting Method.Post in double quotes "", i.e treating it as a string.
Related
I have developed a API using RapidAPI to get and automate test cases to validate response “US” when the value for the input parameter “CurrencyCode” is “USD” Using C# RestSharp.but it is fowing an error when its opening on .net console as below on get and IRestresponse.I need help to fix it.
here is my code.
using RestSharp;
using System;
using RestSharp.Authenticators;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IFSAPI
{
internal class Program
{
static void Main(string[] args)
{
//arrange
var client = new RestClient("https://wft-geo-db.p.rapidapi.com/v1/geo/countries?currencyCode=LKR");
var request = new RestRequest(Method.GET);
//
request.AddHeader("X-RapidAPI-Key", "2ade609583msh867a2c95e9e419dp1a1668jsnf1f880a47cc5");
request.AddHeader("X-RapidAPI-Host", "wft-geo-db.p.rapidapi.com");
//act
IRestResponse response = client.Execute(request);
//var content = response.Content;
//Console.WriteLine(content);
//Console.ReadKey();
}
}
}
What's wrong with this code snippet in C#.NET core 3:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
var uriBuilder = new UriBuilder
{
Scheme = Uri.UriSchemeHttps,
Host = "api.omniexplorer.info",
Path = "v1/transaction/address",
};
var req = new Dictionary<string, string>
{
{ "addr", "1FoWyxwPXuj4C6abqwhjDWdz6D4PZgYRjA" }
};
using(var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(uriBuilder.Uri, new StringContent(JsonConvert.SerializeObject(req)));
response.EnsureSuccessStatusCode();
Console.WriteLine(response.Content.ToString());
}
}
}
}
When running this with a breakpoint at the line response.EnsureSuccessStatusCode(), I always get 502 response. However, if running this in Postman or in curl, I got back a valid result.
Example in curl:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "addr=1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P" "https://api.omniexplorer.info/v1/transaction/address"
Many thanks for helping a newbie out!
The request uses application/x-www-form-urlencoded so instead of StringContent use FormUrlEncodedContent:
var content = new FormUrlEncodedContent(req);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(uriBuilder.Uri, content);
So I have the function to READ from the server:
btnRead.Click += (sender, e) =>
{
showtxt.Text = ShowRemoteStringFile("ftp://url/text.txt");
};
string ShowRemoteStringFile(string readUrl)
{
WebRequest req = WebRequest.Create(readUrl);
req.Credentials = new NetworkCredential("username", "password");
WebResponse rsp = (WebResponse)req.GetResponse();
StreamReader rdr = new StreamReader(rsp.GetResponseStream());
string result = rdr.ReadToEnd();
return result;
}
Now I'm looking for the write functionality but couldn't find anything.. I tried to connect Web Request with SteamWriter but it's a mess.
I think I have to use a completly different approach than from the read function. Anyone out there that could share his C#, Xamarin genius? Thanks in advance.
You can use the System.Net library to do networking. Also you are not doing this async. You should make the button function async as shown below. Just put the contents of your edit box in the string content string. Let me know if you have other questions. I've included using statements too for you. You can get system.http on nuget.
https://www.nuget.org/packages/Microsoft.Net.Http/
using System;
using System.Text;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
async Task<string> ShowRemoteStringFile(string readUrl){
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", Username, Password))));
httpClient.DefaultRequestHeaders.Add("Accept", "text/plain; charset=UTF-8");
var body = new StringContent("your http post body text", Encoding.UTF8, "application/json");
Task<System.Net.Http.HttpResponseMessage> r = httpClient.PostAsync("YOUR_URL", body);
// do stuff while waiting for response to come back
var response = await r; //await the request to return a result from the server
var responseContent = response.Content;
if (response.IsSuccessStatusCode){
//Do stuff with the response content
}
}
Now to make your button async so you can await inside the button event:
btnRead.Click += async (sender, e) =>
{
await ShowRemoteStringFile("string");
};
Let me know if you have any questions :)
I'm trying to develop a web API, and when I test the POST method, the body is always null. I have tried everything when sending the request:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/SomeAPI");
req.Method = "post";;
var aaa = Encoding.Default.GetBytes("Test");
req.ContentType = "application/xml";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream())) {
Console.WriteLine(sr.ReadToEnd());
}
I use a breakpoint, and the API is called properly, but the body member is always null:
[HttpPost]
public void Post([FromBody]String test) {
}
try
[HttpPost]
public void SomeApi()
{
var test = HttpContext.Current.Request.Form["Test"];
}
If u send correctly the value,this will work 100%
Your Content Type is set to XML so you must pass the data as XML. This means wrapping your data in <string> element.
I would recommend using RestSharp (http://restsharp.org/) for making WebAPI calls from .Net.
var client = new RestClient("http://localhost:1748/");
var request = new RestRequest("api/SomeAPI", Method.POST);
request.AddBody("Test");
var response = client.Execute(request);
Update
I have created a sample project and it works absolutely fine:
Server side:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class HomeController : ApiController
{
[Route("api/TestAPI")]
[HttpPost]
public IHttpActionResult Post([FromBody]String test)
{
return Ok(string.Format("You passed {0}.", test));
}
}
}
Client side:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/TestAPI");
req.Method = "post"; ;
var aaa = Encoding.Default.GetBytes("\"Test\"");
req.ContentType = "application/json";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
}
After installing the WEB API service in IIS and running the console app it prints:
"You passed Test."
Please note the quotes around the response.
If you want to use XML then you need to modify the content type and data you are sending:
var aaa = Encoding.Default.GetBytes("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Test</string>");
The response you will get is
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">You passed Test.</string>
Both samples in the debugger will have correct value passed in the test parameter.
Two things to try, 1st, try your request using a tried and tested tool like Postman. This will eliminate any chance your request is malformed in any way. 2nd, try changing your ContentType to text/plain. It's possible the request pipeline is seeing application/xml but your request body is invalid xml which really should be a bad request but is just being serialized as null.
Akamai api using purge my url i got eror he authorization header does not have the right format
getting error response httpresponse any one tell how to add header authorization in c# tell how to solve the issue ,,tell me how to call akamai api in our project .i have accesstoken and cilent token secret key also how to add this token in this header section
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Net.Http.Headers;
public partial class Purge : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
purge();
}
public async static void purge()
{
var baseAddress = new Uri(" https://akab-wbrwrbgi6t5urrvg-ohjpi4v6gxsib5aa.purge.akamaiapis.net/");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("akab-jbl3s3ptctwvocrr-3fawkhddo47udqlg");
// httpClient.DefaultRequestHeaders.ExpectContinue = false;
using (var content = new StringContent("{ \"objects\": [ \"http://hindi.eenaduindia.com/News/National/2016/03/15150007/video-viral-of-a-girl-creating-ruckus-in-hyderabad.vpf\" ], \"action\": \"remove\", \"type\": \"arl\", \"domain\": \"production\"}", System.Text.Encoding.Default, "application/json"))
{
using (var response = await httpClient.PostAsync("ccu/v2/queues/default", content))
{
string responseData = await response.Content.ReadAsStringAsync();
var b = responseData.Replace('"', ' ');
var r = b.Split(',', '\n');
// Response.Write(r[1]);
}
}
}
}
}
You need to use an Akamai signing library. There is a library for C# here:
https://github.com/akamai-open/AkamaiOPEN-edgegrid-C-Sharp
The library's README includes sample code to get started integrating it into your system.
Thanks,
Kirsten