简体   繁体   English

HTTPClient POST方法C#

[英]HTTPClient POST method c#

I guess this has been asked a million times, but I cannot figure out how stuff works. 我猜这已经被问了一百万遍了,但是我无法弄清楚这些东西是如何工作的。 My app is in c# against framework 4.0. 我的应用程序在针对框架4.0的C#中。 I try to do a simple POST, but my POST doens't even get triggered, not from C#. 我尝试做一个简单的POST,但是我的POST甚至都不会被触发,而不是C#。 It does get triggered by a simple PowerShell equivalent that looks like this : 它确实是由一个类似以下内容的简单PowerShell触发的:

$uri="http://localhost:50554/api/pinfo/?sendmessage=yes&message=yep&killprocess=yes&timeout=20"
Invoke-RestMethod -uri $uri -Method Post -Body @($apso | ConvertTo-Json) -ContentType "application/json; charset=utf-8"

Where $apso is an array of custom PSObjects. 其中$ apso是自定义PSObjects的数组。 Hence, the POST method works and is available. 因此,POST方法有效并且可用。 So in C# I do: 因此,在C#中,我这样做:

// this needs to be POSTed
PInfo pi = new PInfo();
pi.computername="test";
pi.username="test";
pi.PID="1234";
List<PInfo> lpi=new List<PInfo>();
lpi.Add(pi);

//Invoke the POST
HttpClient client = new HttpClient();

client.BaseAddress = new Uri("http://localhost:50554/");
var a = client.PostAsync("api/pinfo/?sendmessage=yes&message=tralala&killprocess=no&timeout=20", new StringContent(lpi.ToString(), System.Text.Encoding.UTF8, "application/json"))
             .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());

But that doesn't trigger the same POST? 但这不会触发相同的POST吗? Any ideas what I am missing here? 有什么想法我在这里想念的吗?

BR, Ronald 罗纳德·BR

Edit:: await gives me a compile error: The 'await' operator can only be used within an async method. 编辑::等待给我一个编译错误:“等待”运算符只能在异步方法中使用。 Consider marking this method with the 'async' modifier and changing its return type to 'Task'. 考虑使用“异步”修饰符标记该方法,并将其返回类型更改为“任务”。

If anyone can explain what that means, great! 如果有人能解释这意味着什么,太好了! Really no idea. 真的不知道

But this also seems to solve it: 但这似乎也可以解决它:

PInfo p = new PInfo();
p.username = "test";
p.computername = "test";
p.PID = "test";
List<PInfo> testlist = new List<PInfo>();
testlist.Add(p);

client.BaseAddress = new Uri ("http://localhost:50554");

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage result = client.PostAsJsonAsync(url, testlist).Result;

string resultContent = result.Content.ReadAsStringAsync().Result;

The await keyword can only be used in a method that is decorated with the async keyword eg: await关键字只能在以async关键字修饰的方法中使用,例如:

private async void button_click(object sender, EventArgs e) {
    var foo = await SomeMethodAsync(...);
}

In this regard, use of await is a bit viral - it requires all calling methods up to the root to be marked async. 在这方面,使用await有点病毒-它要求直到根的所有调用方法都被标记为异步。 As to why async exists see this SO question about the subject . 至于为什么存在异步,请参见关于主题的SO问题

You've discovered the other way to use this API. 您已经发现了使用此API的另一种方法。 These new style Async methods return a Task if there is a result or just a Task if there is no result. 这些新样式的Async方法如果有结果,则返回一个Task;如果没有结果,则仅返回一个Task。 In this case, you could also do this: 在这种情况下,您也可以这样做:

Task<HttpResponseMessage> task = client.PostAsync("api/pinfo/?sendmessage=yes&message=tralala&killprocess=no&timeout=20", new StringContent(lpi.ToString(), System.Text.Encoding.UTF8, "application/json"));

HttpResponseMessage response = task.Result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM