英文:
define cache-control header in a json object in C#
问题
// Here's the corrected C# code for building the batch request body with the cache-control header:
var requestBody = new
{
GetEvents = new
{
Method = "GET",
Headers = new
{
CacheControl = "no-cache"
},
Resource = "https://xxxx"
},
GetAttributes = new
{
Method = "GET",
ParentIDs = new[] { "GetEvents" },
RequestTemplate = new
{
Resource = "{0}?selectedFields=Items.Name;Items.Value.Value"
},
Parameters = new[] { "$.GetEvents.Content.Items[*].Links.Value" }
}
};
The issue in your original code was with the use of "Cache-Control"
in the Headers
object, which is not a valid C# property name due to the hyphen. In the corrected code, I've used "CacheControl"
(without the hyphen) as the property name, and it should work as intended.
英文:
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?
答案1
得分: 0
以下是已翻译的内容:
一个更简单的方法是只使用一个大的格式字符串:
* 在`@""`字符串内,所有的`"`字符都需要重复一次。
* 在格式字符串内,所有的`{`和`}`字符都需要重复一次。
但最终结果并不是那么难以阅读:
```csharp
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();
// 做一些操作...
}
请注意,我已经将代码部分保留为原始文本。
英文:
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...
}
答案2
得分: 0
这对我有效:
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\"");
英文:
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\"");
</details>
# 答案3
**得分**: -1
谢谢Dai和Serge,两种方法都有效。
我还发现我可以使用以下代码:
```csharp
var reqheader = new JObject
{
{"Cache-Control" , "no-cache"}
};
JObject piWebApiRequestBody = JObject.FromObject(new
{
GetEvents = new
{
Method = "GET",
Headers = reqheader,
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")
}
});
```
<details>
<summary>英文:</summary>
Thank you Dai and Serge, both ways works.
I also found I can use this
var reqheader = new JObject
{
{"Cache-Control" , "no-cache"}
};
JObject piWebApiRequestBody = JObject.FromObject(new
{
GetEvents = new
{
Method = "GET",
Headers = reqheader,
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")
}
});
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论