我使用Web api selef host:
public class TestController : ApiController
{
[HttpPost]
public void Testp([FromBody]string title)
{
Console.WriteLine("Post");
}
}
这是一个简单的控制器这是我的客户:
client.BaseAddress = new Uri("http://localhost:1010");
const string englishTitle = "TesteDelete";
var post = client.PostAsync("Test/Testp", new
{
title = englishTitle
}, new JsonMediaTypeFormatter());
var result = post.Result;
if (result.IsSuccessStatusCode)
{
}
else
{
string content = result.Content.ReadAsStringAsync().Result;
}
为什么我的结果是:
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Sun, 21 Apr 2013 12:00:03 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 165
Content-Type: application/json; charset=utf-8
}}
我认为我的模型绑定器有一些错误
我想您正在使用visualstudio web服务器进行调试(按时间顺序(。这个端口可以随时更改,所以我猜它不再是您的URL:中指定的"1010">
"http://localhost:1010"
也许您应该查看此处以自动获取当前URL。
我发现我的问题是,如果我没有用"/"结束基本URI,并试图将其预挂到客户端。PostAsync(..它不起作用。但如果我将其附加到基本uri,它会这样做,
using (HttpClient client = new HttpClient(handler) { BaseAddress = new Uri("https://test.test.com/somepath/") })
var response = client.PostAsync("Broadcast/Order", content).Result;
工作,同时:
using (HttpClient client = new HttpClient(handler) { BaseAddress = new Uri("https://test.test.com/somepath") })
var response = client.PostAsync("/Broadcast/Order", content).Result;
没有。不知道为什么,但很高兴我很快就弄明白了!
-
如果您使用默认路由,它是RESTful(通过HTTP谓词,而不是RPC,通过方法名称(,所以您不应该发布到
http://localhost:1010/Test/Testp
,而是http://localhost:1010/Test
-
您的操作签名采用字符串,但您正在张贴一个匿名对象。你的POST应该是这样的(注意我们只发送字符串(:
var post = client.PostAsync("Test", englishTitle, new JsonMediaTypeFormatter());
var url = URL;
var data = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("client_id", FRAppConfigKeys.GetValue("ClientId")),
new KeyValuePair<string, string> ("client_secret", FRAppConfigKeys.GetValue("ClientSecret")),
new KeyValuePair<string, string>("grant_type", FRAppConfigKeys.GetValue("GrantType") ),
new KeyValuePair<string, string>("username", FRAppConfigKeys.GetValue("UserName")),
new KeyValuePair<string, string> ("password", FRAppConfigKeys.GetValue("Password"))
}
);
HttpResponseMessage response = client.PostAsync(url, data).Result;
var result = response.Content.ReadAsStringAsync().Result;
Dictionary<string, string> tokenDictionary =
JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
string token = tokenDictionary["access_token"];
我也面临同样的问题。但现在解决了。您可以使用此代码。它真的会对你有帮助。