CET
CET

Reputation: 302

How to PATCH data using System.Net.Http

I have uploaded a file to SharePoint and found out what id it has. Now I need to update some of the other columns on that listitem. The problem is that System.Net.Http.HttpMethod.Patch doesn't exist.

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(HttpMethod.Put, updateurl);
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        request.Content = new StringContent(content, Encoding.UTF8, "application/json");
        response = await httpClient.SendAsync(request);
        var responseString = await response.Content.ReadAsStringAsync();
        return responseString;
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

Upvotes: 19

Views: 22833

Answers (3)

LZ_MSFT
LZ_MSFT

Reputation: 4208

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

Upvotes: 22

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59318

It dependents whether .NET Core or .NET Framework is utilized, in case of `.NET Core HttpClient.PatchAsync Method could be utilized.

In case of .NET Framework ListItem could be updated like this:

using (var client = new HttpClient())
{
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
     client.BaseAddress = new Uri("https://graph.microsoft.com");

     var listItemPayload = new Dictionary<string, object>
     {
        {"Color", "Fuchsia"},
        {"Quantity", 934}
     };

     var requestContent = new StringContent(JsonConvert.SerializeObject(listItemPayload));
     requestContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
     var response = await client.PatchAsync(new Uri($"https://graph.microsoft.com/v1.0/sites/{siteId}/lists/{listId}/items/{itemId}/fields"), requestContent);
     var data = response.Content.ReadAsStringAsync().Result.ToString();
}

where PatchAsync is the extension method for HttpClient class:

public static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent iContent)
    {
        var method = new HttpMethod("PATCH");
        var request = new HttpRequestMessage(method, requestUri)
        {
            Content = iContent
        };

        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            response = await client.SendAsync(request);
        }
        catch (TaskCanceledException e)
        {
            Debug.WriteLine("ERROR: " + e.ToString());
        }

        return response;
    }
}

All the credits for extension method go to the author of this answer

Upvotes: 10

Szab
Szab

Reputation: 1263

Can't you just use the HttpMethod class constructor?

new HttpMethod("PATCH");

Source: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpmethod.-ctor?view=netframework-4.7.2#System_Net_Http_HttpMethod__ctor_System_String_

Upvotes: 8

Related Questions