Upload file to OneDrive using RestAPI - c#

I am trying to upload an image to OneDrive using below code. The file was successfully uploaded to the OneDrive folder but when I download the file manually from OneDrive, it opens in black color and shows Invalid Image.
var client = new RestClient("https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content");
var request = new RestRequest(Method.PUT);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", Path.GetExtension(originalFileName).GetMimeType());
request.AddHeader("Authorization", "Bearer " + GetAccessToken());
request.AddFile("content", System.IO.File.ReadAllBytes(filePath), originalFileName);
var response = client.Execute(request);
I really do not know what mistake I am making in here. May you please help me?

Inspired from this SO answer
I need to change it to HttpClient from RestClient. After change the code will like:
using (var client = new HttpClient())
{
var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());
byte[] sContents = System.IO.File.ReadAllBytes(filePath);
var content = new ByteArrayContent(sContents);
var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}

Related

Restsharp get text Files from Server

I'm new to Restsharp. I got a client request and in these "Files" are ten text files.
With this request, I want to return all file names shown in my console, but when I run it, the console is still empty and I don't know why...
Maybe someone can help me :)
var client = new RestClient("http://localhost:12345/files/");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer");
request.AddParameter("application/json", "{\n\n\t\"Username\": \"" + username + "\",\n\t\"Password\": \"" + password + "\",\n\t\"DeviceID\": \"Test\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Unable to pass file to web api in ASP.NET MVC Core

I am working on an angular and .NET Core application. I have to pass the file uploaded from angular to WEB API. My code is:
public async Task ImportDataScienceAnalytics(string authToken, IFormFile file)
{
var baseUrl = Import.GetBaseURL();
var client = new RestClientExtended(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", authToken);
string jsonBody = JsonConvert.SerializeObject(file);
request.AddJsonBody(jsonBody);
var response = await client.ExecutePostTaskAsync(request);
var result = response.Content;
}
Issue is that i get "No Attachment Found". I think the issue is because of IFormFile. How can i resolve this issue so that i can upload the file to web api.
It seems that you'd like to post uploaded file to an external API from your API action using RestClient, you can refer to the following code snippet.
var client = new RestClient(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", authToken);
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
request.AddFile("file", fileBytes, file.FileName, "application/octet-stream");
}
//...
Testing code of Import action
public IActionResult Import(IFormFile file)
{
//...
//code logic here
You need to make following changes to the code.
var baseUrl = Import.GetBaseURL();
var client = new RestClientExtended(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
byte[] data;
using (var br = new BinaryReader(file.OpenReadStream()))
data = br.ReadBytes((int)file.OpenReadStream().Length);
ByteArrayContent bytes = new ByteArrayContent(data);
MultipartFormDataContent multiContent = new MultipartFormDataContent
{
{ bytes, "file", file.FileName }
};
//request.AddHeader("authorization", authToken);
//string jsonBody = JsonConvert.SerializeObject(file);
//request.AddJsonBody(jsonBody);
/// Pass the multiContent into below post
var response = await client.ExecutePostTaskAsync(request);
var result = response.Content;
Do not forget to pass the variable multiContent into the post call.

How to upload "Binary" data through "oneNote API"

I need to upload multiple images to oneNote through "oneNote API", but I don't know how to write binary to code.
Here's the code in my code:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken(provider));
string imagePartName = "imageBlock1";
StringBuilder simpleHtml = new StringBuilder();
simpleHtml.Append("<html lang=\"zh-CN\">\n");
simpleHtml.Append("<head>\n");
simpleHtml.Append("<title>" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "</title>\n");
simpleHtml.Append("<meta name=\"created\" content=\"" + DateTime.Now.ToString("o") + "\" />\n");
simpleHtml.Append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />\n");
simpleHtml.Append("</head>\n");
simpleHtml.Append("<body data-absolute-enabled=\"true\" style=\"font-family:Microsoft YaHei;font-size:11pt\">\n");
simpleHtml.Append("<img src=\"name:"+ imagePartName + "\" alt=\"a cool image\" width=\"500\"/>");
simpleHtml.Append("</body>\n");
simpleHtml.Append("</html>");
var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "/pages")
{
Content = new MultipartFormDataContent
{
{
new StringContent(simpleHtml.ToString(), Encoding.UTF8, "text/html"), "Presentation"
}, //Here is the HTML data
//How to add "binary" data here
}
};
response = await client.SendAsync(createMessage);
Looking forward to everyone's reply!
If you want to use MultipartFormDataContent you can convert your binary data to Base64 string (example).
Drawback of this is the amount of characters you need to transfer.
There're several methods in MultipartFormDataContent that concerns 'stream'. It would be worth to look into those.

HTTP Request with Basic Auth always returns 401

I'm trying to do a GET in an UWP (Windows 10) app. I've tried several ways but all always return 401.
In Postman it works fine, but I can' seem to get it to work in my app. What am I missing.
These are the methods I tried (all return 401):
Method 1:
var request = WebRequest.Create("http://api.fos.be/person/login.json?login=200100593&password=pass");
request.Headers["Authorization"] = "Basic MYAUTHTOKEN";
var response = await request.GetResponseAsync();
Method 2:
const string uri = "http://api.fos.be/person/login.json?login=200100593&password=pass";
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("MYUSERNAME", "MYPASSWORD");
using (var client = new HttpClient(httpClientHandler))
{
var result = await client.GetAsync(uri);
Debug.WriteLine(result.Content);
}
Method 3:
var client = new RestClient("http://api.fos.be/person/login.json?login=200100593&password=pass");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "e2f84b21-05ed-2700-799e-295f5470c918");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic MYAUTHTOKEN");
IRestResponse response = await client.Execute(request);
Debug.WriteLine(response.Content);
The third method is code generated straight from Postman, so why is it working there and not in my app?
This thread helped me figure out the solution. I was using http:// but I had to make it https://. HTTPS with the code in that thread was the solution.
This is my final code:
public static async void GetPerson()
{
//System.Diagnostics.Debug.WriteLine("NetworkConnectivityLevel.InternetAccess: " + NetworkConnectivityLevel.InternetAccess);
//use this, for checking the network connectivity
System.Diagnostics.Debug.WriteLine("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//var msg = new Windows.UI.Popups.MessageDialog("GetIsNetworkAvailable: " + System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable());
//msg.ShowAsync();
HttpClient httpClient = new HttpClient();
// Assign the authentication headers
httpClient.DefaultRequestHeaders.Authorization = CreateBasicHeader("MYUSERNAME", "MYPASS");
System.Diagnostics.Debug.WriteLine("httpClient.DefaultRequestHeaders.Authorization: " + httpClient.DefaultRequestHeaders.Authorization);
// Call out to the site
HttpResponseMessage response = await httpClient.GetAsync("https://api.fos.be/person/login.json?login=usern&password=pass");
System.Diagnostics.Debug.WriteLine("response: " + response);
string responseAsString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine("response string:" + responseAsString);
}
public static AuthenticationHeaderValue CreateBasicHeader(string username, string password)
{
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
String logindata = (username + ":" + password);
System.Diagnostics.Debug.WriteLine("AuthenticationHeaderValue: " + new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)));
return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
I would try this first:
Check your "MYAUTHTOKEN", it is usually a combo of username:password and is base 64 encoded. So if your username was "user" and password was "pass" you would need to base64 encode "user:pass"
var request = WebRequest.Create("https://api.fos.be/person/login.json");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Text.Encoding.UTF8.GetBytes("user:pass"));
var response = await request.GetResponseAsync();

RestSharp - Authorization Header not coming across to WCF REST service

I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
System.Net.HttpRequestHeader.Authorization,
"Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
}
When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);
What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");
will come thru, only "Authorization" seems stripped out/missing.
instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
I used milano's answer to get my REST service call to work (using GET)
Dim client2 As RestClient = New RestClient("https://api.clever.com")
Dim request2 As RestRequest = New RestRequest("me", Method.GET)
request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
Dim response2 As IRestResponse = client2.Execute(request2)
Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")
The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header
You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

Categories

Resources