【问题标题】:How to return a new type from Web API post?如何从 Web API 帖子返回新类型?
【发布时间】: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


【解决方案1】:

我自己构建了这个通用函数作为发布到Web API的助手

用法

var result = PostAsync<MyDataType, MyResultType>("http://...", MyData)

功能

public async Task<U> PostAsync<T, U>(string url, T model)
{
    using (HttpClient httpClient = new HttpClient(httpHandler))
    {
        var result = await httpClient.PostAsJsonAsync<T>(url, model);

        if (result.IsSuccessStatusCode == false)
        {
            string message = await result.Content.ReadAsStringAsync();
            throw new Exception(message);
        }
        else
        {
            return await result.Content.ReadAsAsync<U>();
        }
    }
}

并且HttpClientHandler 配置为 Windows 身份验证

protected HttpClientHandler httpHandler = new HttpClientHandler() { PreAuthenticate = true, UseDefaultCredentials = true };

【讨论】:

  • 你的 httpHandler 变量中有什么?我尝试使用此代码,但它从未进入 IsSuccessStatusCode 条件测试。刚从 result = await 行返回。很奇怪。
  • 这是我为 Windows Auth 配置的 HttpClientHandler,HttpClientHandler httpHandler = new HttpClientHandler() { PreAuthenticate = true, UseDefaultCredentials = true };
  • 仍然没有得到我想要的东西。我每次返回的响应对象如下所示:Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" AsyncState: null CancellationPending: false CreationOptions: None Exception: null ID:1 结果:null 状态:WaitingForActivation
  • @HapiDjus 那是Task类型的结果。您需要等待或获取 ReadAsStringAsync() 的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
相关资源
最近更新 更多