Rest Api in Sharepoint for Special Fields like Assignedto in TaskList

Sharepoint updates issue

You can update the “Assigned To” field of a SharePoint Task List item using the REST API by sending a POST request with a JSON payload to the item’s endpoint.

Since “Assigned To” is a Person or Group field, you need to use the User ID (the ID from the site’s User Information List) for the new assignee.

 

📝 REST API JSON Payload Structure

 

The key to updating the “Assigned To” field is the specific property name and value format in the JSON body:

Field Required Value Notes
__metadata Type object Specifies the entity type (SP.Data.[ListName]ListItem).
AssignedToId Integer or Array of Integers Crucial: You must use the internal field name appended with Id. The value is the target user’s ID.

 

💻 Example C# Implementation (Using HttpClient)

 

Here is how you would construct the JSON and the POST request using C#’s HttpClient class.

 

1. Find the User ID

 

Before running this, you need the Site User ID for the user you want to assign the task to. You can get this by using the _api/web/ensureuser endpoint:

HTTP

 
POST /_api/web/ensureuser('i:0#.f|membership|user@tenant.onmicrosoft.com')

The response will contain the Id you need.

 

2. C# Code to Update the Task

 

C#

 
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

public async Task UpdateTaskAssignedTo(string siteUrl, string accessToken, string listName, int itemId, int newAssigneeId)
{
    // 1. Define the item type name.
    // The convention is SP.Data.[ListName]ListItem (e.g., SP.Data.TasksListItem)
    string itemEntityType = $"SP.Data.{listName.Replace(" ", string.Empty)}ListItem";

    // 2. Construct the REST API endpoint URL.
    string apiUrl = $"{siteUrl}/_api/web/lists/getbytitle('{listName}')/items({itemId})";

    // 3. Construct the JSON payload.
    // Use 'AssignedToId' with the user's ID.
    string jsonBody = $@"{{
        ""__metadata"": {{ ""type"": ""{itemEntityType}"" }},
        ""AssignedToId"": {newAssigneeId}
    }}";

    using (var client = new HttpClient())
    {
        // Set the Authorization header (for SharePoint Online/Add-in Authentication)
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        
        // Indicate the request is an update (MERGE method)
        client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE"); 
        
        // Pass the ETag header to avoid concurrency issues (Use * to ignore checks for simple updates)
        client.DefaultRequestHeaders.Add("IF-MATCH", "*"); 

        // Set the content type
        var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

        // Execute the request
        HttpResponseMessage response = await client.PostAsync(apiUrl, content);

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Task {itemId} in {listName} successfully updated and assigned to User ID: {newAssigneeId}.");
        }
        else
        {
            // Log or handle the error response
            string error = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Error updating task: {response.StatusCode} - {error}");
        }
    }
}

 

Multiple Users

 

If the “Assigned To” field allows multiple users, you must format the AssignedToId value as an array of integers:

JSON

 
// JSON Payload for multiple assignment
string jsonBodyMulti = $@"{{
    ""__metadata"": {{ ""type"": ""{itemEntityType}"" }},
    ""AssignedToId"": {{
        ""__metadata"": {{ ""type"": ""Collection(Edm.Int32)"" }},
        ""results"": [ 12, 15, 20 ] // Array of User IDs
    }}
}}";

You would replace the simple integer newAssigneeId in the C# code with this more complex JSON structure for multiple users.

Ps

Ps

# GENERATE NEW CERT (RUN ONCE)

$thumbprint = “0FE10549F0278B6B9D14A4C43C72B716479FD41C”

# get existing cert
$existingCertificate = Get-Item -Path Cert:\LocalMachine\My\$thumbprint

# generate a new cert based on the existing one one
$newCertificate = New-SelfSignedCertificate -CloneCert $existingCertificate

 

# COPY NEW CERT TO TRUSTED ROOT CERT AUTHORITIES STORE

$thumbprint = “0FE10549F0278B6B9D14A4C43C72B716479FD41C”

# get existing cert
$certificate = Get-Item -Path Cert:\LocalMachine\My\$thumbprint

# generate temp password and path
$guid = [Guid]::NewGuid().ToString() | ConvertTo-SecureString -AsPlainText -Force
$path = [System.IO.Path]::GetTempFileName()

# export cert
$certificate | Export-PfxCertificate -FilePath $path -Password $guid

# import cert to Trusted Root Store
Import-PfxCertificate -FilePath $path -Exportable -Password $guid -CertStoreLocation Cert:\LocalMachine\Root

# delete temp cert
Remove-Item -Path $path -Force

 

# APPLY TO CERT TO SERVICE BUS

$thumbprint = “0FE10549F0278B6B9D14A4C43C72B716479FD41C”

Set-SBCertificate -FarmCertificateThumbprint $thumbprint -EncryptionCertificateThumbprint $thumbprint

Stop-SBFarm # RUN ONCE ON WFM SERVER

Update-SBHost # RUN ONCE ON ALL WFM SERVERS

Start-SBFarm # RUN ONCE ON WFM SERVER, THIS TAKES SEVERAL MINUTES TO RUN

How to replace/update code for System.Net.Mail SmtpClient Class with Mailkit

How to replace/update code for System.Net.Mail SmtpClient Class with Mailkit SmtpClient Class

As most of us have seen this warning.

SmtpClient Class

Definition

Namespace:

System.Net.Mail

Assemblies:

System.dll, netstandard.dll, System.Net.Mail.dll

Warning

This API is now obsolete.

Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The SmtpClient type is now obsolete.

Microsoft reference Link

https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8

MimeKit and MailKit are popular fully-featured email frameworks for .NET.

So how to convert you code from Old format to new.

Adding MailKit to your project via NuGet

· In Visual Studio‘s Package Manager Console, enter the following command:

· Install-Package MailKit

If you are writing a new code its good to use samples provided on Mailkit site.

Mailkit code

var message = new MimeMessage ();

message.From.Add (new MailboxAddress (“Joey”, “joey@friends.com”));

message.To.Add (new MailboxAddress (“joey@friends.com”, “alice@wonderland.com”));

message.To.Add (new MailboxAddress (“Alice”, “alice@wonderland.com”));

message.Subject = “How you doin?”;

message.Body = new TextPart (“html”) {

Text = @”Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on

Saturday and I was hoping you could make it.

Will you be my +1?

— Joey

};

public static void SendMessages (IList<MimeMessage> messages)

{

using (var client = new SmtpClient ()) {

client.Connect (“smtp.gmail.com“, 465, SecureSocketOptions.SslOnConnect);

client.Authenticate (“username”, “password”);

foreach (var message in messages) {

client.Send (message);

}

client.Disconnect (true);

}

}

If you have old code then follow these easy conversions.

Now check your old code

If you have “Recipientlist” value=”jane@contoso.com,ben@contoso.com”

Then MailboxAddress will not parse it.

It should be converted to this format.

“jane@contoso.com”,

“ben@contoso.com”

You will note that the MimeMessage body is no more of String type (TextPart).

Sample code for conversion.

using System.Net.Mail;

private void sendemailclick()

{

try

{

MailMessage mail = new MailMessage();

SmtpClient SmtpServerclient = new SmtpClient(“smtp.gmail.com“);

mail.From = new MailAddress(“your_email_address@gmail.com”);

mail.To.Add(“to_address”);

mail.Subject = “Test Mail – 1”;

mail.IsBodyHtml = true;

string htmlBody;

htmlBody = “Write some HTML code here”;

mail.Body = htmlBody;

SmtpServerclient.Port = 587;

SmtpServerclient.Credentials = new System.Net.NetworkCredential(“username”, “password”);

SmtpServerclient.EnableSsl = true;

SmtpServerclient.Send(mail);

}

catch (Exception ex)

{

Console.WriteLine(ex.ToString());

}

}

This is the method which comes handy

Importing from System.Net.Mail

To make things even simpler still, MimeKit allows you to explicitly cast a MailMessage to a MimeMessage

Since Smtpclient is  obsolete but not the mail message, We
can still leverage MailMessage. It had very great
parse method for email address separated with comma and mail body as string.

using MailKit.Net.Smtp;

using MimeKit;

using System.Text;

using oldsmtp=System.Net.Mail

using MailKit.Security;

private void sendemailclick()

{

try

{

oldsmtp.MailMessage mail = new oldsmtp.MailMessage();

SmtpClient SmtpServerclient = new SmtpClient();

//this is needed if certificate is bad or self signed.

SmtpServerclient.ServerCertificateValidationCallback = (s, c, h, e) => true;

SmtpServerclient.Connect(“smtp.gmail.com“, 465, SecureSocketOptions.SslOnConnect);

SmtpServerclient.Authenticate(“username”, “password”);

mail.From = new oldsmtp.MailAddress(“your_email_address@gmail.com”);

mail.To.Add(“your_email_address@gmail.com,your_email_address@gmail.com,your_email_address@gmail.com”);

mail.Subject = “Test Mail – 1”;

mail.IsBodyHtml = true;

string htmlBody;

htmlBody = “Write some HTML code here”;

SmtpServerclient .Send(MimeMessage.CreateFromMailMessage(mail));

}

catch (Exception ex)

{

Console.WriteLine(ex.ToString());

}

}