IHttpActionResult WEB API响应标头

时间:2015-12-05 04:25:38

标签: asp.net-web-api2 asp.net-web-api

我正在使用IHttpActionResult类型进行API调用Get调用,我想在上面的同一个调用中发送响应标头是我的代码

[HttpGet]
    public IHttpActionResult GetSyncData()
    {
        syncDataRepository.Location = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.Location);
        syncDataRepository.UserLocation = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.UserLocation);
        syncDataRepository.UserAuthentication = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.UserAuthentication);
        syncDataRepository.UserDetails = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.UserDetails);
        syncDataRepository.TourOrganization = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.TourOrganization);
        syncDataRepository.TourBatch = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.TourBatch);
        syncDataRepository.TourSuperBatch = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.TourSuperBatch);
        syncDataRepository.TourPlanItemChat = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.TourPlanItemChat);
        syncDataRepository.TourBatchPlan = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.TourBatchPlan);
        syncDataRepository.MyRole = JsonConvert.SerializeObject(Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name));
        syncDataRepository.DeletedBatchPlan = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.DeletedBatchPlan);
        syncDataRepository.Mode = JsonConvert.SerializeObject(SyncDataOfMobileDatatSet.Mode);
        string jsonData = JsonConvert.SerializeObject(syncDataRepository);

        return Json(syncDataRepository);
    }

我尝试使用HttpContext.Response,但我将其视为null。有没有别的方法请帮助我。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以通过实现IHttpActionResult并在ExecuteAsync方法中设置标头来设置响应标头,如下所示:

public class DateHeaderActionResult<TContent> : IHttpActionResult
{
  private DateTime _date;
  private TContent _content;
  private HttpRequestMessage _request;

  public DateHeaderActionResult(DateTime date, TContent content, HttpRequestMessage request)
  {
    _date = date;
    _content = content;
    _request = request;
  }

  public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
  {
    var response = _request.CreateResponse(HttpStatusCode.OK);
    response.Headers.Add("MyDate", _date.ToString("yyyyMMddThhmmss"));
    response.Content = new ObjectContent<TContent>(_content, new JsonMediaTypeFormatter());
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    return Task.FromResult(response);
  }
}

然后在你的控制器中而不是返回

return Json(syncDataRepository);

你会回来

return new DateHeaderActionResult<SyncDataRepository>(DateTime.Now, syncDataRepository, Request);

假设syncDataRepository类名是SyncDataRepository