2017-03-19 43 views
3

我收到C#Client-Service中的代碼並使用HTTP協議。 我需要從我在網上找到(不知道我所做的是正確的),我擴大已經存在的BaseHttpActionResult類中添加一個新的動作誰返回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值從響應? 我在網上看到,有方法命名爲內容和標題和一些例子,但我不明白如何使用它...

希望任何輸入。

回答

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; 
+0

正是我需要的,非常感激! –

相關問題