在C#中,在一个JSON对象中定义Cache-Control头部。

huangapple go评论101阅读模式
英文:

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
            {
                {&quot;Cache-Control&quot; , &quot;no-cache&quot;}
            };

            JObject piWebApiRequestBody = JObject.FromObject(new
            {
                GetEvents = new
                {
                    Method = &quot;GET&quot;,
                    Headers = reqheader,
                    Resource = &quot;xxx&quot;
                },
                GetAttributes = new
                {
                    Method = &quot;GET&quot;,
                    ParentIDs = new JArray(&quot;GetEvents&quot;),
                    RequestTemplate = new
                    {
                        Resource = &quot;{0}?selectedFields=Items.Name;Items.Value.Value&quot;
                    },
                    Parameters = new JArray(&quot;$.GetEvents.Content.Items[*].Links.Value&quot;)
                }
            });


</details>



huangapple
  • 本文由 发表于 2023年7月17日 16:13:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定