Kliver Max
Kliver Max

Reputation: 5299

Can not emulate curl request using c# HttpClient

I have a cURL POST request what creates issue in YouTrack:

curl -X POST https://my.youtrack/api/issues \
    -H "Accept: application/json" \
    -H "Authorization: Bearer perm:123" \
    -H "Content-Type: application/json" \
    -d "{\"project\":{\"id\":\"67-74\"},\"summary\":\"REST API lets you create issues!\",\"description\":\"Lets create a new issue using YouTracks REST API.\"}"

Now i trying to do the same using c#:

public async static Task<string> SendPostRequestAsync(string url, string postParams)
{
    try
    {
        HttpClient client = new HttpClient() { BaseAddress = new Uri("https://my.youtrack/") };
        client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "perm:123");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var content = new StringContent(postParams, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("api/issues", content);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();
    }
    catch (Exception ex)
    {
        return null;
    }
}

Sending JSON the same {"description":"Created using REST Api","project":"{\"id\":\"67-74\"}","summary":"Test Issue"}.

But get 500 Internal Server Error. Just can't see what a problem here, im sending json incorrectly?

Upvotes: 0

Views: 470

Answers (2)

phuzi
phuzi

Reputation: 13060

Sending JSON the same {"description":"Created using REST Api","project":"{"id":"67-74"}","summary":"Test Issue"}

Unfortunately, that is not the same as the CURL request as project is originally \"project\":{\"id\":\"67-74\"} - unescaping the quotes gives "project":{"id":"67-74"}. You'll notice that project is an object with an id property.

Your C# "equivalent" has "project":"{\"id\":\"67-74\"}" where project is a string containing {"id":"67-74"} not an object at all.

Fix your JSON and it should work as expected.

Upvotes: 0

golakwer
golakwer

Reputation: 373

I think the problem is the quotes around the object after project, if you do the following then the c# json should match the CURL json

instead of this

{"description":"Created using REST Api","project":"{\"id\":\"67-74\"}","summary":"Test Issue"}

try this

{"description":"Created using REST Api","project":{"id":"67-74"},"summary":"Test Issue"}

which looks like this in escaped for string in c#

"{\"description\":\"Created using REST Api\",\"project\":{\"id\":\"67-74\"},\"summary\":\"Test Issue\"}"

the original json was passing the object after project as a string

Upvotes: 1

Related Questions