簡體   English   中英

C#-Office API返回400“ 69 {”錯誤”:{”代碼”:“ RequestBodyRead”,“消息”:“無法讀取值'0'作為帶引號的JSON字符串值。“}} 0”

[英]C# - Office API returning 400 “69 {”error“:{”code“:”RequestBodyRead“,”message“:”Cannot read the value '0' as a quoted JSON string value.“}} 0 ”

我正在嘗試使用Office 365 API發送電子郵件,我無法使用Microsoft.Office365包進行發送,因為它們目前不支持我們的身份驗證,但是我確實具有有效的令牌來訪問API,獲取請求工作正常,但是當我嘗試發布到“ https://outlook.office.com/api/v2.0/me/sendmail ”時,出現上述錯誤。 雖然無法使用Microsoft.Office365中提供的發送功能,但我使用的是消息對象來創建我的電子郵件,然后進行序列化和發布。

public void SendMail(string Subject, string Body) {
    HttpClient client = new HttpClient();
    string accessToken = userCache.UserAccessToken;
    Uri uri = new Uri("https://outlook.office.com/api/v2.0/me/sendmail");
    client.DefaultRequestHeaders.Add("User-Agent", agent);
    client.DefaultRequestHeaders.Add("client-request-id", requestGuid);
    client.DefaultRequestHeaders.Add("return-client-request-id", "true");
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    List<string> recipients = new List<string>();
    recipients.Add(userCache.Email);

    #region Create Email Message
    Message email = new Message();
    email.Body = new ItemBody();
    email.Body.Content = Body;
    email.Body.ContentType = 0;//0=text, 1=html
    email.From = new Recipient();
    email.From.EmailAddress = new EmailAddress();
    email.From.EmailAddress.Address = userCache.Email;//set from email to email of current logged in user

    email.Importance = Importance.Normal;
    email.Sender = email.From;
    email.Subject = Subject;
    email.ToRecipients = recipients;
    #endregion
    try {
        dynamic mailObject = new ExpandoObject();
        mailObject.Message = email;
        mailObject.SaveToSentItems = "true";
        HttpResponseMessage hrm = client.PostAsJsonAsync<Object>(uri, mailObject as ExpandoObject).Result;
    } catch (Exception e) { }
}

這會將下面的json提交給API:

{
    "Message": {
        "Subject": "Products",
        "Body": {
            "ContentType": 0,
            "Content": "Products"
        },
        "BodyPreview": null,
        "Importance": 0,
        "HasAttachments": null,
        "ParentFolderId": null,
        "From": {
            "EmailAddress": {
                "Name": null,
                "Address":"andrew.branoff@paretobiz.com"
            }
        },
        "Sender": {
            "EmailAddress": {
                "Name": null,
                "Address": "andrew.branoff@paretobiz.com"
            }
        },
        "ToRecipients": [
            {
                "EmailAddress": {
                    "Name": null,
                    "Address": "andrew.branoff@paretobiz.com"
                }
            }
        ],
        "CcRecipients": [],
        "BccRecipients": [],
        "ReplyTo": [],
        "ConversationId": null,
        "UniqueBody": null,
        "DateTimeReceived": null,
        "DateTimeSent": null,
        "IsDeliveryReceiptRequested": null,
        "IsReadReceiptRequested": null,
        "IsDraft": null,
        "IsRead": null,
        "WebLink": null,
        "Attachments": [],
        "ChangeKey": null,
        "Categories": [],
        "DateTimeCreated": null,
        "DateTimeLastModified": null,
        "Id": null
    },
    "SaveToSentItems": "true"
}

據我所知,這是API正在尋找的東西,因為我使用了自己的對象來構建它,但是無論我做什么,它似乎都拒絕了我發送的內容。 我嘗試過使用

JsonConvert.SerializeObject(mailObject, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

不發送空值,因為對於它計算的內容(如正文預覽),它可能不接受值,甚至不接受空值,但沒有任何變化。

由於提供的JSON有效負載無效,因此很可能發生指定的錯誤。

問題與此行有關:

email.Body.ContentType = 0;//0=text, 1=html

Microsoft.OutlookServices.ItemBody ContentType屬性接受字符串值(不是integer ): TextHTML ,例如:

email.Body.ContentType = "Text";

該錯誤表示當API需要字符串值時,您正在發送整數值0 實際上, 這里的文檔顯示Message.Body.ContentType以及Message.Importance應該是字符串,例如:

  "Body": {
    "ContentType": "Text",
    "Content": "Products"
  },

您可能會為這些屬性發送整數值,因為在您的c#類中,它們是枚舉。 如果StringEnumConverter名稱將枚舉序列化為字符串,則需要使用StringEnumConverter

您可以直接在屬性上將其設置為屬性,例如:

public class Body
{ 
    [JsonConverter(typeof(StringEnumConverter))]
    public ContentType ContentType { get; set; }

    public string Content { get; set; }
}

您還可以配置HttpClient以將此轉換器用於所有枚舉,如本答案所述

感謝其他答案的幫助,我找到了解決方案,以修改Json.net序列化對象的方式。 我稍后將發布確切的解決方案,以幫助其他任何人解決此問題。

var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
settings.NullValueHandling = NullValueHandling.Ignore;
string json = JsonConvert.SerializeObject(emailObject, Newtonsoft.Json.Formatting.None, settings);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM