Getting Bad Request error while updating email category with Office 365 API and HttpClient in C#

混江龙づ霸主 提交于 2019-12-08 19:05:33

Finally got solution. Here it is for newbies like me.

What was the error -

When I request API with PATCH with body I was getting Bad Request error.

What I was doing wrong -

When I evaluated my request with this awesome tool for testing outlook 365 API, I come to know the error which was

"error": {
    "code": "RequestBodyRead",
    "message": "An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartArray' node was expected."
}

This error meant I was sending wrong data. I was sending string to a List<string>. This is really silly I know but it happens right? ;)

So, to correct this instead of passing JSON as fixed string, I created a class with a List<string> property as below to have flexibility to input category as want.

public class ChangeEmailCategory
{
    public List<string> Categories { get; set; }

}

And here is final method.

//Passing parameters - AuthenticationResult, URI with authentication header, List of categories.
public string UpdateCategory(AuthenticationResult result, string uriString,List<string> categories)
    {
        //HTTPMethod.PATCH not available so adding it manualy.
        var httpMethod = new HttpMethod("PATCH");
        HttpRequestMessage request = new HttpRequestMessage(httpMethod, uriString);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
        ChangeEmailCategory cec = new ChangeEmailCategory();
        cec.Categories = categories;
        //Serializing class properties as JSON
        var jsonData = JsonConvert.SerializeObject(cec);
        //Adding JSON to request body
        request.Content =new StringContent(jsonData,Encoding.UTF8, "application/json");
        HttpResponseMessage response = httpClient.SendAsync(request).Result;
        if (!response.IsSuccessStatusCode)
            throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);
        return response.Content.ReadAsStringAsync().Result;
    }

Here is method call.

List<string> categories = new List<string>();
categories.Add("Checking");
//utility is my class containing method
utility.UpdateCategory(result, categoryChangeUri, categories);

That's all! It took me one day to learn and figure it out. Thanks to all posts on Stack Overflow and google which I referred but not remember not to mention here.

If anyone need any additional information regarding this do let me know. Just mention me in comments. I will try to help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!