RestClient AddFile throwing FileNotFoundException but file is there - c#

I want to upload a file to S3, I have the signedUrl as param
RestClient AddFile throwing FileNotFoundException but the file is there
public async Task <string> UploadFile(string signUrl, string fileId, string fileName, string filePath)
{
var client = new RestClient(signUrl);
var request = new RestRequest(signUrl, Method.Put);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddFile(fileName, filePath); // Expection here!
System.Console.WriteLine("File was uploaded");
// upload the file
RestResponse response = await client.ExecuteAsync(request);
return response.Content;
}
from the debugger:
fileName: "sample-file1.json"
filePath: "/Users/user1/dev/projects/biot-device-sample-csharp/BioT.DeviceSample/BioT.DeviceSample/bin/Debug/netcoreapp3.1/assets"
when I do cat command in terminal I can print the file content

Related

"Converted/Optimized" C# Code - HTTP Client Response Code 404 Error

I'm trying after "converted/optimized" a C# Unity Project to my Visual Studio in C# to work for me (the code)...
i used this github lib for nft.storage
https://github.com/filipepolizel/unity-nft-storage/blob/main/NFTStorageClient.cs
If i call then with:
string pathtofile = #"" + AppDomain.CurrentDomain.BaseDirectory + "testfile.txt";
await NFTStorageTest.Upload(NFTStorageTest.nftStorageApiUrl, pathtofile);
i get this error:
System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found). at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() at Main.net.NFTStorageTest.Upload(String uri, String pathFile) in C:\...\NFTStorageTest.cs:line 173
Here is my Code:
// nft.storage API endpoint
internal static readonly string nftStorageApiUrl = "https://api.nft.storage/";
// HTTP client to communicate with nft.storage
internal static readonly HttpClient nftClient = new HttpClient();
// http client to communicate with IPFS API
internal static readonly HttpClient ipfsClient = new HttpClient();
// nft.storage API key
public string apiToken = "XXX";
public void Start()
{
nftClient.DefaultRequestHeaders.Add("Accept", "application/json");
if (apiToken != null)
{
nftClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiToken);
}
else
{
// log in console in case no API key is found during initialization
Console.WriteLine("Starting NFT Storage Client without API key, please call 'SetApiToken' method before using class methods.");
}
}
public async Task<NFTStorageUploadResponse> UploadDataFromFile(string path)
{
StreamReader reader = new StreamReader(path);
string data = reader.ReadToEnd();
reader.Close();
Console.WriteLine("Uploading...");
return await UploadDataFromString(data);
}
public async Task<NFTStorageUploadResponse> UploadDataFromString(string data)
{
string requestUri = nftStorageApiUrl + "/upload";
string rawResponse = await Upload(requestUri, data);
string jsonString = JsonConvert.SerializeObject(rawResponse);
NFTStorageUploadResponse parsedResponse = JsonConvert.DeserializeObject<NFTStorageUploadResponse>(jsonString);
return parsedResponse;
}
public static async Task<string> Upload(string uri, string pathFile)
{
byte[] bytes = File.ReadAllBytes(pathFile);
using (var content = new ByteArrayContent(bytes))
{
content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
//Send it
var response = await nftClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
Stream responseStream = await response.Content.ReadAsStreamAsync();
StreamReader reader = new StreamReader(responseStream);
return reader.ReadToEnd();
}
}`
whats my mistake and how can i fix it?
await NFTStorageTest.Upload(NFTStorageTest.nftStorageApiUrl, pathtofile);
This should be called with
$”{NFTStorageTest.nftStorageApiUrl}upload”
See the original file
https://github.com/filipepolizel/unity-nft-storage/blob/45bedb5c421982645bc9bf49d12beed8f2cdb9d3/NFTStorageClient.cs#L297

HTTP CLIENT Upload File C#

This is the code below (C#) To upload in https://nft.storage/ It Works fine But when I upload mp4 file (Uploaded successfully) , The uploaded file doesn’t work . Source Code https://github.com/filipepolizel/unity-nft-storage
I used many different HTTPCLIENT example but it same
broken Uploaded mp4 File: http://ipfs.io/ipfs/bafybeibt4jqvncw6cuyih27mujbpdmsjl46pykablvravh3qg63vuvcdqy
// nft.storage API endpoint
private static readonly string nftStorageApiUrl = "https://api.nft.storage/";
// HTTP client to communicate with nft.storage
private static readonly HttpClient nftClient = new HttpClient();
// http client to communicate with IPFS API
private static readonly HttpClient ipfsClient = new HttpClient();
// nft.storage API key
public string apiToken;
void Start()
{
nftClient.DefaultRequestHeaders.Add("Accept", "application/json");
if (apiToken != null)
{
nftClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiToken);
}
else
{
// log in console in case no API key is found during initialization
Debug.Log("Starting NFT Storage Client without API key, please call 'SetApiToken' method before using class methods.");
}
}
public async Task<NFTStorageUploadResponse> UploadDataFromFile(string path)
{
StreamReader reader = new StreamReader(path);
string data = reader.ReadToEnd();
reader.Close();
print("Uploading...");
return await UploadDataFromString(data);
}
public async Task<NFTStorageUploadResponse> UploadDataFromString(string data)
{
string requestUri = nftStorageApiUrl + "/upload";
string rawResponse = await Upload(requestUri, data);
NFTStorageUploadResponse parsedResponse = JsonUtility.FromJson<NFTStorageUploadResponse>(rawResponse);
return parsedResponse;
}
private async Task<string> Upload(string uri, string paramString)
{
try
{
using (HttpContent content = new StringContent(paramString))
{
//content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
HttpResponseMessage response = await nftClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
Stream responseStream = await response.Content.ReadAsStreamAsync();
StreamReader reader = new StreamReader(responseStream);
return reader.ReadToEnd();
}
}
catch (HttpRequestException e)
{
Debug.Log("HTTP Request Exception: " + e.Message);
Debug.Log(e);
return null;
}
}
the answer helped me . thanks , I changed the Update method to :
public static async Task<string> Upload(string uri, string pathFile)
{
byte[] bytes = System.IO.File.ReadAllBytes(pathFile);
using (var content = new ByteArrayContent(bytes))
{
content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
//Send it
var response = await nftClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
Stream responseStream = await response.Content.ReadAsStreamAsync();
StreamReader reader = new StreamReader(responseStream);
return reader.ReadToEnd();
}
}
It works great now

C# HttpClient: How to send query strings in POST Requests

This is the POST Request, it works.
curl -X POST --header 'Accept: application/json'
'http://mywebsite.com/api/CompleteService?refId=12345&productPrice=600'
How to send this request using C# => HttpClient => client.PostAsync() method?
Two methods have been tried but both failed.
Method 1 (Failed, Response 404)
string url = "http://mywebsite.com/api/CompleteService";
string refId = "12345";
string price= "600";
string param = $"refId ={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;
This would only work if API is to accept a request body, not query strings.
Method 2 (Failed, Response 404)
https://stackoverflow.com/a/37443799/7768490
var parameters = new Dictionary<string, string> { { "refId ", refId }, { "productPrice", price} };
var encodedContent = new FormUrlEncodedContent(parameters);
HttpResponseMessage response = client.PostAsync(url, encodedContent)
Apparently, None of the tried approaches put parameters in the URL!. You are posting on the below URL
"http://mywebsite.com/api/CompleteService"
However, something that works
string url = "http://mywebsite.com/api/CompleteService?";
string refId = "12345";
string price= "600";
string param = $"refId={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
Attach Parameters to URL and to get Response's Body, Use:
try
{
HttpResponseMessage response = await client.PostAsync(url + param, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("Message :{0} ",e.Message);
}

Upload File and Convert to Base64 (406 Error Not Acceptable )

What I am trying to do here is that I am going to send a converted pdf to base64 to an endpoint where in this is the endpoint
HTTP-HEADERS:
api-key: your-key
Content-Type: application/json
Request Body JSON
{
"file":
{
"mime": "application/pdf",
"data": "base64-data="
}
}
and here's how I Upload and Convert the my file
public async Task UploadFile()
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; //user canceled selecting image
string fileName = fileData.FileName;
string contents = Encoding.UTF8.GetString(fileData.DataArray);
var stream = fileData.GetStream();
var bytes = new byte[stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string base64 = Convert.ToBase64String(bytes);
File ru = new File();
ru.mime = "application/pdf";
ru.data = "base64-data="+base64;
string url = "ENDPOINT URL";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders
.Accept
.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string jsonData = JsonConvert.SerializeObject(ru);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
requestMessage.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("api-key", "API KEY HERE");
requestMessage.Headers.Add("Accept-Encoding", "gzip");
HttpResponseMessage response = await client.SendAsync(requestMessage);
string result = await response.Content.ReadAsStringAsync();
if(result!= null)
{
resultLabel = result;
}
now it gives me the error
{"Message":"HTTP 406 Not Acceptable. There was an error with your request. Please check your payload and then try again,","Result":406}
By following the suggestion of #Jason in the comment section I have solved my problem
https://learning.postman.com/docs/sending-requests/generate-code-snippets/
Hope this solves someone having thesame problem as mine.

How to use RestSharp's AddFile() method to send httpContext.Request.Files[0]?

I am using RestSharp to call .NET Web API.
I am sending the uploaded excel file to web api. Below code works perfectly fine on local machine.
But on the server, we don't have permission to save the uploaded file.
I am looking for alternate method for restRequest.AddFile("content", location) that accept HttpPostedFileBase postedFile = httpContext.Request.Files[0].
RestClient restClient = new RestClient("http://localhost:56360");
RestRequest restRequest = new RestRequest("api/excelupload/Upload");
int readWriteTimeout = restRequest.ReadWriteTimeout > 0
? restRequest.ReadWriteTimeout
: ReadWriteTimeout;
restRequest.ReadWriteTimeout = readWriteTimeout;
restRequest.Method = Method.POST;
restRequest.AddHeader("Content-Type", "multipart/form-data");
restRequest.AddFile("content", location);
restRequest.AddParameter("DetailLineNumber", "4");
var response = restClient.Execute(restRequest);
File reading on API.
foreach (var content in provider.Contents)
{
if (!string.IsNullOrWhiteSpace(content.Headers.ContentDisposition.FileName))
{
postedData.File = await content.ReadAsByteArrayAsync();
}
}
I have not used RestSharp for a while. Could you use a Stream? Something like this:
public RestRequest CreateUploadFileRequest(string path, string filename, Stream fileStream)
{
var request = new RestRequest (Method.POST);
request.Timeout = int.MaxValue; //test
request.Resource = "/files/{path}";
request.AddParameter ("path", path, ParameterType.UrlSegment);
//Need to add the "file" parameter with the file name
request.AddParameter ("file", filename);
request.AddFile ("file", s => StreamUtils.CopyStream (fileStream, s), filename);
return request;
}

Categories