Having 403 error while uploading file to sharepoint using RestAPI - .net-core

I am trying to upload a file to my sharepoint folder using RestAPI but everytime i received status code 403 forbidden. As i am implementing this in dot net core console application so i need to use RestAPI because of "SharePointOnlineCredentials" is no more supported in core. Any help would be much appreciated. Below i pasted my existing code .Thanks !!
byte[] bytefile = System.IO.File.ReadAllBytes("D:/4.txt");
string hostWeb = "https://xxx.sharepoint.com/sites/xxxProjects";
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(hostWeb + "/_api/web/GetFolderByServerRelativeUrl('/sites/xxx/Shared%20Documents/Folder1')/Files/add(url='4.txt',overwrite=true)");
endpointRequest.Method = "POST";
endpointRequest.ContentType = "application/json";
endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
endpointRequest.GetRequestStream().Write(bytefile, 0, bytefile.Length);
HttpWebResponse endpointresponse = (HttpWebResponse)endpointRequest.GetResponse();

You can use PnP Core to upload files to SharePoint. Check this link on how to do it with PnP Core.
https://pnp.github.io/pnpcore/using-the-sdk/files-intro.html#adding-files-uploading

Related

Uploading files to SharePoint OnPremise 2016 using .NET Core 5.0 and HttpWebRequest C#

SharePoint CSOM is not supported in .NET Core 5.0, so I'm trying to use HttpWebRequest to upload files to SharePoint 2016 on-premise.
This code sample shown here works in .NET 4.7, however it throws errors when run on .NET Core.
public async Task<string> UploadFile(string folderName, string fileName, byte[] file)
{
// Url to upload file
string resourceUrl = _sharePointUrl + $"/_api/web/GetFolderByServerRelativeUrl('/opportunity/{folderName}')/Files/add(url='{fileName}',overwrite=true)";
HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
wreq.Credentials = _credentials;
wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
// Get formdigest value from site
wreq.Headers.Add("X-RequestDigest", GetFormDigest());
wreq.Headers.Add("binaryStringRequestBody", "true");
wreq.Method = "POST";
wreq.Accept = "application/json; odata=verbose";
wreq.ContentLength = file.Length;
wreq.Timeout = 100000;
await wreq.GetRequestStream().WriteAsync(file, 0, file.Length);
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
return response.StatusDescription;
}
Errors are listed below. The errors are happening on the
HttpWebResponse response = (HttpWebResponse)wreq.GetResponse();
line.
System.AggregateException: 'One or more errors occurred. (An error occurred while sending the request.)'
Inner Exception 1: WebException: An error occurred while sending the request.
Inner Exception 2: HttpRequestException: An error occurred while sending the request.
Inner Exception 3: IOException: The response ended prematurely.
What am I missing?
Does the HttpWebRequest in .NET Core work differently than the .NET framework version?
Do I need to use different headers or configure the request object differently?
Thanks in advance.

WooCommerce rest api access failing with httpWebRequest

I am trying to get WooCommerce data using WooCommerce v3 API from c#.
When I use below url in browser I get the products data as json;
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890
When I use url
https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products
and
consumer_key = ck_12345678901234567890 and consumer_secret = cs_12345678901234567890
as Params in Postman then I get the products data as well. So the credentials and url are valid.
However when I try to do this using HttpWebRequest it fails with "The remote server returned an error: (401) Unauthorized" exception. My code is below and the exception appears on the last line of code.
The vales in HttpWebRequest before the GetResponseAsync call can be seen here.
What am I doing wrong?
Thanks
Regards
string wc_url = "https://MyUsername:MyPassword#mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890";
HttpWebRequest httpWebRequest = null;
httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url);
httpWebRequest.AllowReadStreamBuffering = false;
WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);

Windows 10 Universal App - Package doesn't work normally as debug mode

public async Task<List<Tip>> GetTips()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://APIURL ");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = await request.GetResponseAsync();
StreamReader sr = new StreamReader(res.GetResponseStream());
string result = sr.ReadToEnd();
List<Tip> tips = JsonConvert.DeserializeObject<List<Tip>>(result);
return tips;
}
I am working on a project which need to consume an enterprise Web API(Https) and display the data on Win 10 live tile, it’s an UWP application.
But I found it only works when I ran it in IDE(Visual Studio 2015 debug mode) .
When I created a package for this app and run it by powershell for installation, request.GetResponseAsync method throws exception “The login request was denied”.
I tried to check Enterprise Authentication and Private Networks(Client & Server) options in Package.appxmanifest. But there was no effect.
Any idea how to make it work normally? Thanks.

Google Drive APi with clean WEB API 2

i wanted to use the Google Drive API along with a simple WEB API 2 - Project.
Somehow the GoogleWebAuthorizationBroker.cs is missing.
What i use:
Visual Studio 2013 Update 4
Empty Template with WEB API
My steps:
Creating the empty project including WEB API
building the project
updating packages via Nuget Packager
Install-Package Google.Apis.Drive.v2 (using this guide: https://developers.google.com/drive/web/quickstart/quickstart-cs)
Copy and Paste the code from the above link into a clean api-controller:
public IEnumerable<string> Get()
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "228492645857-5599mgcfnhrr74a7er1do1chpam4rnbt.apps.googleusercontent.com",
ClientSecret = "onoyJQaUazQK4VsKUjD63sDu",
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
byte[] byteArray = System.IO.File.ReadAllBytes(#"C:\Projects\VS\DataAnime\DataAnime\document.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
return new string[] { file.Id, "value2" };
}
building
6.1 Error: GoogleWebAuthorizationBroker.cs is missing
6.2 Google says following error in browser:
That’s an error.
Error: redirect_uri_mismatch
Application: Project Default Service Account
You can email the developer of this application at: xxxx#gmail.com
The redirect URI in the request: http://example.com:63281/authorize/ did not match a registered
redirect URI.
http://example.com:63281/authorize/ was neither the url i am using for my project nor the url i registered in my developer console (this errorshowing-port is changeing everytime i run this project.
Has anyone an idea why is that?
No other sources helped fixing this weird issue.
I solved it by creating a new project on https://console.developers.google.com for a native software instead of a web-client project, even i am using a web client.
There is just one weird thing:
If i debug my code, it still says that GoogleWebAuthorizationBroker.cs is missing.
Without debugging i can do everything i want.
Thank you very much for your help.

Do I need to investigate HTTP 401 cached by Fiddler during the HttpWebRequest post to ASP.NET WebApi server

I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data.
To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors
{"Message":"Authorization has been denied for this request."}
Steping step by step in debuger I fund that following lines of code doing 401 error
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Credentials = new NetworkCredential(username, password);
wr.Method = "POST";
wr.ContentType = "application/json";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
}
Later in code when I do wr.GetResponse() I do get status 200OK.
My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?
If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:
Composer tab -> Options tab -> Automatically Authenticate
Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");
HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;

Resources