在C#中的json对象中定义cache-control头

xzlaal3s  于 2023-08-08  发布在  C#
关注(0)|答案(3)|浏览(131)

我需要发布一个来自C#代码的批处理API请求。在批处理中的一个请求中,我需要将Cache-Cotrol设置为no-cache。请求体应该是这样的: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"
    ]
  }
}

字符串
我试图在C#中使用匿名类型构建主体,如以下代码,但我得到编译错误。

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")
                }
            });


以下是错误:匿名类型成员声明符无效。匿名类型成员必须使用成员赋值、简单名称或成员访问权限来声明。
我做了一些搜索,注意到问题是缓存控件的名称中有“-”,这在C#命名中是不允许的,所以编译器选择了它。我做了一些搜索,但找不到任何解决办法来处理这个问题。
我还尝试设置cache-control,将其添加为内容的Header和批处理post请求的DefaultRequestHeader(在主体中包含get请求),但它没有相同的效果。我需要将它添加到主体中的一个get请求的头中,就像我之前在postman请求中显示的那样,以获得我需要的结果。
有人能帮助我如何创建主体并按预期包含缓存控件吗?

8tntrjer

8tntrjer1#

更简单的方法是使用一个巨大的format-string:

  • @""字符串中,所有"字符都需要加倍。
  • 在format-string中,所有{}字符都需要加倍。

但最终的结果并不是那么不可读:

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...
}

字符串

sbdsn5lh

sbdsn5lh2#

这对我很有效

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\"");

字符串

xa9qqrwz

xa9qqrwz3#

谢谢戴和塞奇,两种方式都有效。我还发现我可以用这个

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")
            }
        });

字符串

相关问题