.net 有没有办法用Microsoft-Graph C#客户端库删除消息?

pcrecxhr  于 2023-01-31  发布在  .NET
关注(0)|答案(3)|浏览(147)

我在我的C#. net项目中使用Microsoft Graph客户端,我注意到Message项没有公开任何用于删除消息的方法。
我试过了

client.Me.Messages[mail.Id].Delete()

我发现Delete方法不存在。
我该怎么办?

vsaztqbk

vsaztqbk1#

您需要创建包含DeleteAsync()方法的Request对象:

graphServiceClient
    .Me
    .Messages["your message id"]
    .Request()
    .DeleteAsync();

基于您自己的代码:

await client
  .Me
  .Messages[mail.Id]
  .Request()
  .DeleteAsync();
nfs0ujit

nfs0ujit2#

我没有使用过这个客户端库,但我看过its Github repo。从repo文档中不太清楚如何删除消息,但MS Graph文档指出有一种方法可以通过其API删除消息:
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/message_delete
但是,基于客户机repo,看起来您只需要创建一个MessageRequest并调用它的DeleteAsync()方法。
MessageRequest类接受一个请求url,它可能是消息url(类似于/me/messages/{id})。

wpcxdonn

wpcxdonn3#

我用了这个:

public static async Task DeleteEmail(string emailId)
        {
            TokenCache tokens = TokenCacheHelper.GetUserCache();
            PublicClientApplication clientApp = new PublicClientApplication(secret, RootAuthUri, tokens);

            using (HttpClient c = new HttpClient())
            {
                string requestURI = RootUri + "/me/messages/" + emailId;

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, requestURI);
                //Authentication token
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await GetTokenAsync(clientApp));

                HttpResponseMessage response = await c.SendAsync(request);
                string responseString = await response.Content.ReadAsStringAsync();
            }

        }

private static async Task<string> GetTokenAsync(PublicClientApplication app)
        {
            AuthenticationResult result = null;
            string[] scopes = { "User.Read", "Mail.ReadWrite" };
            try
            {

                // Get the token from the cache.
                result = await app.AcquireTokenSilentAsync(scopes, (await app.GetAccountsAsync()).FirstOrDefault());
                return result.AccessToken;
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilentAsync. 
                // This indicates you need to call AcquireTokenAsync to acquire a token
                Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    // Dialog opens for user.
                    result = await app.AcquireTokenAsync(scopes);
                    return result.AccessToken;
                }
                catch (MsalException msalex)
                {
                    Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
                    return null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}");
                return null;
            }
        }

static class TokenCacheHelper
    {

        /// <summary>
        /// Get the user token cache
        /// </summary>
        /// <returns></returns>
        public static TokenCache GetUserCache()
        {
            if (usertokenCache == null)
            {
                usertokenCache = new TokenCache();
                usertokenCache.SetBeforeAccess(BeforeAccessNotification);
                usertokenCache.SetAfterAccess(AfterAccessNotification);
            }
            return usertokenCache;
        }

        static TokenCache usertokenCache;

        /// <summary>
        /// Path to the token cache
        /// </summary>
        public static readonly string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.bin";

        private static readonly object FileLock = new object();

        public static void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {

            lock (FileLock)
            {
                args.TokenCache.Deserialize(File.Exists(CacheFilePath)
                    ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath),
                                              null,
                                              DataProtectionScope.CurrentUser)
                    : null);
            }
        }

        public static void AfterAccessNotification(TokenCacheNotificationArgs args)
        {
            // if the access operation resulted in a cache update
            if (args.TokenCache.HasStateChanged)
            {
                lock (FileLock)
                {
                    // reflect changesgs in the persistent store
                    File.WriteAllBytes(CacheFilePath,
                                       ProtectedData.Protect(args.TokenCache.Serialize(),
                                                             null,
                                                             DataProtectionScope.CurrentUser)
                                      );
                    // once the write operationtakes place restore the HasStateChanged bit to filse
                    args.TokenCache.HasStateChanged = false;
                }
            }
        }
    }

相关问题