skip to Main Content

I need to post a batch API request from a C# code. In one of the requests in the batch, I need to set Cache-Cotrol to no-cache. The request body should be like this:
request body in postman

{
  "GetEvents": {
    "Method": "GET",
    "Resource": "https://xxxx",
    "Headers": {"CacheControl": "no-cache"}
  },
  "GetAttributes": {
    "Method": "GET",
    "ParentIDs": [
      "GetEvents"
    ],
    "RequestTemplate": {
      "Resource": "{0}?selectedFields=Items.Name;Items.Value.Value"
    },
    "Parameters": [
      "$.GetEvents.Content.Items[*].Links.Value"
    ]
  }
}

I am trying to build the body in C# using anonymous types like the following code, but I get compile error.

GetEvents = new
                {
                    Method = "GET",
                    Headers = new 
           {
            Cache-Control  = "no-cache"
           },
                    Resource = "xxx"
                },
                GetAttributes = new
                {
                    Method = "GET",
                    ParentIDs = new JArray("GetEvents"),
                    RequestTemplate = new
                    {
                        Resource = "{0}?selectedFields=Items.Name;Items.Value.Value"
                    },
                    Parameters = new JArray("$.GetEvents.Content.Items[*].Links.Value")
                }
            });

Here is the error:
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

I did some search and noticed the problem is that cache-control has “-“ in the name which of course in not allowed in C# naming so complier pick it. I have done some search but could not find any workaround to handle this.

I also tried to set the cache-control by adding it as both the Header of the content and DefaultRequestHeader of the the batch post request (with the get requests in the body) but it does not have the same effect. I need to add it to the header of one of the get requests in the body as I showed in the postman request previously to get the result I need.

Can someone please help me how I can create the body and include the cache-control as intended?

2

Answers


  1. A simpler approach is to just use a giant format-string:

    • Within @"" strings, all " chars need to be doubled-up.
    • Within a format-string, all { and } chars need to be doubled-up.

    But the end-result isn’t that unreadable:

    const String JSON_FMT = @"
    {{
      ""GetEvents"": {{
        ""Method"": ""GET"",
        ""Resource"": ""https://xxxx"",
        ""Headers"": {{""CacheControl"": ""no-cache""}}
      }},
      ""GetAttributes"": {{
        ""Method"": ""GET"",
        ""ParentIDs"": [
          ""GetEvents""
        ],
        ""RequestTemplate"": {{
          ""Resource"": ""{0}?selectedFields=Items.Name;Items.Value.Value""
        }},
        ""Parameters"": [
          ""$.GetEvents.Content.Items[*].Links.Value""
        ]
      }}
    }}
    ";
    
    Uri resourceUri = new Uri( @"https://something?databaseWebId=F..." );
    
    String jsonBody = String.Format( CultureInfo.InvariantCulture, JSON_FMT, resourceUri );
    
    using StringContent reqBody = new StringContent( jsonBody, "application/json" );
    using HttpRequestMessage req = new HttpRequestMessage( HttpMethods.Post, reqBody  );
    using( HttpResponseMessage resp = await httpClient.SendAsync( req ) )
    {
        String respBody = await resp.Content.ReadAsStringAsync();
    
        _ = resp.EnsureSuccessStatusCode();
    
        // do stuff...
    }
    
    Login or Signup to reply.
  2. this works for me

    var obj = new
        {
            GetEvents = new
            {
                Method = "GET",
                Headers = new
                {
                    Cache_Control = "no-cache"
                },
                Resource = "xxx"
            },
            GetAttributes = new
            {
                Method = "GET",
                ParentIDs = new JArray("GetEvents"),
                RequestTemplate = new
                {
                    Resource = "{0}?selectedFields=Items.Name;Items.Value.Value"
                },
                Parameters = new JArray("$.GetEvents.Content.Items[*].Links.Value")
            }
    
        };
    
    string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented)
                             .Replace(""Cache_Control"", ""Cache-Control"");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search