PATCH Async requests with Windows.Web.Http.HttpClient class
I found how to do a "custom" PATCH
request with the previous System.Net.Http.HttpClient
class here, and then fiddled with until I made it work in the Windows.Web.Http.HttpClient
class, like so:
public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) {
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri) {
Content = iContent
};
HttpResponseMessage response = new HttpResponseMessage();
// In case you want to set a timeout
//CancellationToken cancellationToken = new CancellationTokenSource(60).Token;
try {
response = await client.SendRequestAsync(request);
// If you want to use the timeout you set
//response = await client.SendRequestAsync(request).AsTask(cancellationToken);
} catch(TaskCanceledException e) {
Debug.WriteLine("ERROR: " + e.ToString());
}
return response;
}
Patch request using C# with HTTP client - Microsoft Graph
Replace GetAsync with this in your code
var httpclient = GetHttpClient(accessToken.Result);
var response = await client.SendAsync(new HttpRequestMessage(new HttpMethod("PATCH"), "https://graph.microsoft.com/v1.0/me/messages"));
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
JObject o = JObject.Parse(content);
How to PATCH data using System.Net.Http
Modify the code as below.
public static async Task<string> UpdateFileData()
{
var (authResult, message) = await Authentication.AquireTokenAsync();
string updateurl = MainPage.rooturl + "lists/edd49389-7edb-41db-80bd-c8493234eafa/items/" + fileID + "/";
var httpClient = new HttpClient();
HttpResponseMessage response;
try
{
var root = new
{
fields = new Dictionary<string, string>
{
{ "IBX", App.IBX }, //column to update
{ "Year", App.Year}, //column to update
{ "Month", App.Month} //column to update
}
};
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
var content = JsonConvert.SerializeObject(root, s);
var request = new HttpRequestMessage(new HttpMethod("PATCH"), updateurl);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
request.Content = new StringContent(content, System.Text.Encoding.UTF8, "application/json;odata=verbose");
response = await httpClient.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
catch (Exception ex)
{
return ex.ToString();
}
}
Or we can also use REST API to update list item by ID.
Refer to: SharePoint 2013 REST Services using C# and the HttpClient
How do I do a patch request using HttpClient in dotnet core?
As of Feb 2022
###Original Answer###
As of .Net Core 2.1, the PatchAsync()
is now available for HttpClient
Reference:
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.patchasync
C# - Xamarin forms add custom header PATCH
You should be able to send a completely custom request with the HttpClient
. Since PATCH
isn't a very common verb, there isn't a shorthand for it.
From the top of my head, try something like this:
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, url) {
Content = new StringContent(
JsonConvert.SerializeObject(add_list_to_folder),
Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);
If you have to use it at several places, it might be just as neat to wrap it in an extension method, like:
public static async Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent httpContent)
{
// TODO add some error handling
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri) {
Content = httpContent
};
return await client.SendAsync(request);
}
Now you should be able to call it directly on your HttpClient
like the post or get methods, i.e.:
var client = new HttpClient();
client.PatchAsync(url, new StringContent(
JsonConvert.SerializeObject(add_list_to_folder),
Encoding.UTF8, "application/json"));
PATCH request to the service doesn't work within my C# application, but works in Fiddler
Your POST
, PUT
and PATCH
requests are missing a body. How should the service handing the request know what you want to change on the resource? You need to set the Content
property on the HttpRequestMessage
.
See this answer for an example.
How do I use the new HttpClient from Windows.Web.Http to download an image?
This is what I eventually came up with. There is not much documentation around Windows.Web.Http.HttpClient
and a lot of the examples online use old mechanisms like ReadAllBytesAsync which are not available with this HttpClient.
I should note that this question from MSDN helped me out a lot, so thanks to that person. As the comment over there states, this guy must be the only person in the world who knows about Windows.Web.Http
!
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Windows.Storage.Streams;
using Windows.Web.Http;
public class ImageLoader
{
public async static Task<BitmapImage> LoadImage(Uri uri)
{
BitmapImage bitmapImage = new BitmapImage();
try
{
using (HttpClient client = new HttpClient())
{
using (var response = await client.GetAsync(uri))
{
response.EnsureSuccessStatusCode();
using (IInputStream inputStream = await response.Content.ReadAsInputStreamAsync())
{
bitmapImage.SetSource(inputStream.AsStreamForRead());
}
}
}
return bitmapImage;
}
catch (Exception ex)
{
Debug.WriteLine("Failed to load the image: {0}", ex.Message);
}
return null;
}
}
Related Topics
Wcf Httptransport: Streamed VS Buffered Transfermode
How to Read Image Pixels' Values as Rgb into 2D Array
Get Affected Rows on Executenonquery
How to Add Http Header to Soap Client
Select Either a File or Folder from the Same Dialog in .Net
System.Io.File.Create Locking a File
Controls in Container Form Come Over Child Form
How to Get All Cookies of a Cookiecontainer
Is There Any Performance Difference Between ++I and I++ in C#
Iapplicationactivationmanager::Activateapplication in C#
How to Add the Same Column to All Entities in Ef Core
Fill Panel with Gradient in Three Colors
How to Dispose of a Backgroundworker