【发布时间】:2014-12-09 15:45:27
【问题描述】:
我正在尝试想出一种方法,用一个对象发布到 Web API 控制器,但返回一个不同的、已处理的对象。我找到的方法都没有解决这个问题。
这是我在 MVC 项目中发布到我的 Web API 项目的方法
public dynamic PostStuff<X>(string action, X request)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var task = client.PostAsJsonAsync(new Uri("host/api/somecontroller/post, request);
task.Wait();
var response = task.Result;
return response;
}
}
这是我的 Web API 控制器代码
public HttpResponseMessage Post([FromBody] FooObject foo)
{
var res = Request.CreateResponse(HttpStatusCode.OK,
new ValidationResponse<FooObject>
{
ID = new Random().Next(1000, 1000000),
Content =
new List<IContent>()
{
{
new Content()
{
Name = "TheContent",
Type = "SomeType",
Value = "This is some content for the page : " + foo.Bar
}
}
},
Product = new ProductFoo(),
Validated = true
});
return res;
}
}
当我中断我的 WebAPI 控制器代码时, res 变量被正确创建。一旦处理返回到 PostStuff 方法,我得到的只是一个 StreamResponse,没有在 Web API 控制器中创建的 ValidationResponse 对象的踪迹。没有错误,但除了帖子成功之外,我无法在回复中使用任何内容。如何从我的发布方法中提取 ValidationResponse?
【问题讨论】:
-
你不能把
response转换成HttpResponseMessage吗? -
你应该使用
await而不是.Wait()。 -
它已经作为 HttpResponseMessage 回来了。即使我从控制器返回一个自定义类型,PostAsJsonAsync 总是返回一个不包含我需要的数据的 HttpResponseMessage。还有什么我可以用来完成 post->return new type->在我的页面任务上使用它的吗?
-
另外,如果我尝试使用 await vs task.Wait(),我会收到一条消息,指出 HttpResponseMessage 不可等待;
标签: c# asp.net-mvc asp.net-web-api