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
A simpler approach is to just use a giant format-string:
@""
strings, all"
chars need to be doubled-up.{
and}
chars need to be doubled-up.But the end-result isn’t that unreadable:
this works for me