Use Variable in StringContent

axb*_*eit 0 c# string json

Is it possible to have a variable in StringContent?

Currently my Code looks like this (It's about \"text\": \"this is my message\"):

myRequestMessage.Content = new StringContent("{\"type\": \"message\", \"text\": \"this is my message\", \"from\": {\"id\": \"myID\", \"name\": \"myName\"}}", System.Text.Encoding.UTF8, "application/json");
Run Code Online (Sandbox Code Playgroud)

But I want to have it like this (\"text\": "+myOwnString+"):

myOwnString = "this is my text";
myRequestMessage.Content = new StringContent("{\"type\": \"message\", \"text\": "+myOwnString+", \"from\": {\"id\": \"myID\", \"name\": \"myName\"}}", System.Text.Encoding.UTF8, "application/json");
Run Code Online (Sandbox Code Playgroud)

My problem is when doing it like I want to have it I get a StatusCode 400, ReasonPhrase: Bad Request from var myResponse = await myClient.SendAsync(myRequestMessage);. So I assume I have to write it differently to make it work.

Does anyone know a fix?

stu*_*rtd 5

如果您将匿名类型序列化而不是使用串联,则这种操作将变得更容易,更易读且更可靠:

var output = new {
    type = "message",
    text = "this is any message you want it to be",
    from = new {
            id = "myId",
            name = "myName"
    }
};

var outputJson = JsonConvert.SerializeObject(output);

Run Code Online (Sandbox Code Playgroud)

结果:

{
  "type": "message",
  "text": "this is any message you want it to be",
  "from": {
    "id": "myId",
    "name": "myName"
  }
}
Run Code Online (Sandbox Code Playgroud)