Shu*_*osh 6 rest c#-4.0 asp.net-mvc-4 asp.net-web-api dotnet-httpclient
我想调用Api函数(1st).来自使用HttpClient的第二个Api功能.但我总是得到404错误.
第一个Api函数(EndPoint: http:// localhost:xxxxx/api/Test /)
public HttpResponseMessage Put(int id, int accountId, byte[] content)
[...]
Run Code Online (Sandbox Code Playgroud)
第二个Api功能
public HttpResponseMessage Put(int id, int aid, byte[] filecontent)
{
WebRequestHandler handler = new WebRequestHandler()
{
AllowAutoRedirect = false,
UseProxy = false
};
using (HttpClient client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://localhost:xxxxx/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var param = new object[6];
param[0] = id;
param[1] = "/";
param[2] = "?aid=";
param[3] = aid;
param[4] = "&content=";
param[5] = filecontent;
using (HttpResponseMessage response = client.PutAsJsonAsync("api/Test/", param).Result)
{
return response.EnsureSuccessStatusCode();
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是.我能像我一样从HttpClient发布方法参数作为对象数组吗?我不想将模型作为方法参数传递.
我的代码有什么问题?
更改代码后无法获得任何响应
return client.PutAsJsonAsync(uri, filecontent)
.ContinueWith<HttpResponseMessage>
(
task => task.Result.EnsureSuccessStatusCode()
);
Run Code Online (Sandbox Code Playgroud)
要么
return client.PutAsJsonAsync(uri, filecontent)
.ContinueWith
(
task => task.Result.EnsureSuccessStatusCode()
);
Run Code Online (Sandbox Code Playgroud)
你可能已经发现了,不,你不能.当您调用时PostAsJsonAsync,代码会将参数转换为JSON并将其发送到请求正文中.您的参数是一个JSON数组,它看起来像下面的数组:
[1,"/","?aid",345,"&content=","aGVsbG8gd29ybGQ="]
Run Code Online (Sandbox Code Playgroud)
这不是第一个功能所期望的(至少这是我想象的,因为你还没有显示路线信息).这里有几个问题:
byte[](引用类型)的参数在请求的主体中传递,而不是在URI 中传递(除非您使用[FromUri]属性显式标记参数).代码看起来像这样:
var uri = "api/Test/" + id + "/?aid=" + aid;
using (HttpResponseMessage response = client.PutAsJsonAsync(uri, filecontent).Result)
{
return response.EnsureSuccessStatusCode();
}
Run Code Online (Sandbox Code Playgroud)
现在,上面的代码还有另一个潜在的问题.它正在等待网络响应(这是当你.Result在Task<HttpResponseMessage>返回的属性中访问属性时发生的情况PostAsJsonAsync.根据环境,可能发生的更糟糕的是它可能会死锁(等待网络响应将到达的线程).最好的情况是这个线程在网络调用期间会被阻塞,这也是不好的.考虑使用异步模式(等待结果,Task<T>在你的行动中返回一个),就像在下面的例子中一样
public async Task<HttpResponseMessage> Put(int id, int aid, byte[] filecontent)
{
// ...
var uri = "api/Test/" + id + "/?aid=" + aid;
HttpResponseMessage response = await client.PutAsJsonAsync(uri, filecontent);
return response.EnsureSuccessStatusCode();
}
Run Code Online (Sandbox Code Playgroud)
或者没有async/await关键字:
public Task<HttpResponseMessage> Put(int id, int aid, byte[] filecontent)
{
// ...
var uri = "api/Test/" + id + "/?aid=" + aid;
return client.PutAsJsonAsync(uri, filecontent).ContinueWith<HttpResponseMessage>(
task => task.Result.EnsureSuccessStatusCode());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40388 次 |
| 最近记录: |