1

I have a problem on using RestHeart. I want to delete a specific document in MongoDB server and I confirmed the below command works fine in command prompt.

http delete localhost:8080/mytest/users/56dda76daeb32b0860d909e1 if-match:56dda76daeb32b0860d909e2

The document was removed correctly and then I created a document in the same collection I wrote some C# code to remove the new created document.

public async void TryDeleteAsync() {
        using(var client = new HttpClient()) {
            client.BaseAddress = new Uri("http://127.0.0.1:8080/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                
            client.DefaultRequestHeaders.IfMatch.Clear();
            client.DefaultRequestHeaders.IfMatch.Add(new EntityTagHeaderValue("\"56dda76daeb32b0860d909e5\""));

            HttpResponseMessage response = await client.DeleteAsync("/mytest/users/56dda76daeb32b0860d909e4");
            if(response.IsSuccessStatusCode) {
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
        }
    }

Document and ETag id are correct but I got response 412 precondtion failed message. What's wrong in this code?

Thanks.

1 Answers1

0

Error 412 - Precondition failed, means that the ETag does not match. Looking at this code line:

client.DefaultRequestHeaders.IfMatch.Add(new EntityTagHeaderValue("\"56dda76daeb32b0860d909e5\""));

I noticed the escaped quotes in the ETag value passed to the EntityTagHeaderValue constructor. Try with:

client.DefaultRequestHeaders.IfMatch.Add(new EntityTagHeaderValue("56dda76daeb32b0860d909e5"));
Andrea Di Cesare
  • 1,125
  • 6
  • 11
  • Thanks Andrea, and I found a related issues: http://stackoverflow.com/a/17344681/6030429 IfMatch.Add() method requires EntityTagHeaderValue but it invokes a format exception if a string does not include quotes. It seems that HttpRequestMessage.Headers.TryAddWithoutValidation("If-Match", "etag") works but I am not sure if this way is correct. – poor debugger Mar 08 '16 at 12:05