如何读取包含Datetime类型的BaseHttpActionResult的响应

时间:2017-03-19 12:17:45

标签: c# .net asp.net-web-api

我收到了使用HTTP协议的C#Client-Service代码。 我需要添加一个返回Datetime类型的新操作,所以我在网上找到的内容(不确定我所做的是正确的)我扩展了已经存在的BaseHttpActionResult类:

public BaseHttpActionResult(HttpStatusCode code, DateTime content)
{
    _code = code;
    _content = content;
}

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
    var response = new HttpResponseMessage
    {
        StatusCode = _code,
        Content = new ObjectContent(typeof(DateTime), _content, new JsonMediaTypeFormatter())
    };

    return Task.FromResult(response);
}

服务添加此操作:

[Route("StatusUpdate")]
[HttpGet]
public IHttpActionResult StatusUpdate()
{
    return new BaseHttpActionResult(HttpStatusCode.OK, DateTime.Today);
}

和客户请求:

public class HttpRequestsHandler
{
    public static DateTime HttpGet(string requestUrl)
    {
        using (var handler = new WebRequestHandler())
        {
            handler.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            using (var httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(requestUrl),
                Timeout = Timeout.InfiniteTimeSpan
            })
            {
                using (var response = httpClient.GetAsync(requestUrl).Result)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        var errorMessage = string.Format("HttpRequestTask: Request failed with status {0} for URL: {1}", response.StatusCode, requestUrl);
                        throw new HttpException(errorMessage, (int)response.StatusCode);
                    }
                    response.???????
                }
            }
        }
    }
}

问题是,如何从响应中读取Datetime值? 我在网上看到有一些名为Content and Headers的方法和一些例子,但我不明白如何使用它......

非常感谢任何意见。

1 个答案:

答案 0 :(得分:2)

过度复杂化的事情。如果你必须返回的是web api终点的日期时间,那么使用现有的功能

[Route("StatusUpdate")]
[HttpGet]
public IHttpActionResult StatusUpdate() {
    return Ok(DateTime.Today);
}

至于获取响应,请使用可用的扩展方法将响应转换为您想要的类型。

var result = response.Content.ReadAsAsync<DateTime>().Result;
return result;

应考虑使用强类型模型。

public class StatusUpdateResponse {
    public DataTime Timestamp { get; set; }
}

导致更新操作......

[Route("StatusUpdate")]
[HttpGet]
public IHttpActionResult StatusUpdate() {
    return Ok(new StatusUpdateResponse { Timestamp = DateTime.Today });
}

var model = response.Content.ReadAsAsync<StatusUpdateResponse>().Result
return model.Timestamp;