简体   繁体   English

Web API Json响应

[英]Web API Json Response

I am developing Web API for my client. 我正在为我的客户开发Web API。 They have suggestion that all response should be a common JSON structure. 他们建议所有响应都应该是通用的JSON结构。

{ Data:"", Status:true, Message:"" }

If error means 如果错误意味着

{ Error:"", Status:false, Message:"" }

Which is the best method to create a common JSON structure as returns. 这是创建通用JSON结构作为返回值的最佳方法。 Now I created a class having these properties. 现在,我创建了一个具有这些属性的类。 And created 2 classes from IHttpActionResult,Error.cs and Success.cs, From that the response is created and returned from the controller. 并从IHttpActionResult,Error.cs和Success.cs创建了2个类,从中创建响应并从控制器返回响应。

The thing is in my controller, 事情在我的控制器里,

public IHttpActionResult GetNewsAndAnnouncements()
    {
        var data = newsAndAnnouncementsDataServices.NewsAndAnnouncements();
        if (data != null && data.Count() > 0)
        {
            return new Success(Request, "News and Announcements Retrieved Successfully", data);
        }
        return new Error(Request, "No News and Announcements Found");
    }

Error.cs Error.cs

public class Error : IHttpActionResult
{
    private readonly string _message;
    private readonly HttpRequestMessage _request;
    private IErrorResponseModel errorResponse;

    public Error(HttpRequestMessage request, string message)
    {
        _message = message;
        _request = request;
        errorResponse = new ErrorResponseModel();
    }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        errorResponse.Message = _message;
        errorResponse.Status = false;
        errorResponse.Error = _message;
        var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new ObjectContent<object>(errorResponse, new JsonMediaTypeFormatter()),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

Success.cs Success.cs

public class Success : IHttpActionResult
{
    private readonly string _message;
    private readonly object _data;
    private readonly HttpRequestMessage _request;
    private IDataResponseModel dataResponse = new DataResponseModel();
    public Success(HttpRequestMessage request, string message, object data)
    {
        _message = message;
        _request = request;
        _data = data;
    } 
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        dataResponse.Message = _message;
        dataResponse.Status = true;
        dataResponse.Data = _data;
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ObjectContent<object>(dataResponse, new JsonMediaTypeFormatter()),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

DataResponseModel.cs DataResponseModel.cs

public class DataResponseModel : Mobility.Common.IDataResponseModel 
{
    public object Data { get; set; }
    public string Message { get; set; }
    public bool Status { get; set; }
}

ErrorResponseModel.cs ErrorResponseModel.cs

public class ErrorResponseModel : Mobility.Common.IErrorResponseModel
{
    public object Error { get; set; }
    public string Message { get; set; }
    public bool Status { get; set; }
}

Is this a right method. 这是正确的方法吗? I need suggestion. 我需要建议。 Is there any other way to achieve this. 还有其他方法可以实现这一目标。 I heard about delegating handler something. 我听说有委派处理程序的事情。 But I don't have much idea on these. 但是我对此并不了解。 Please help me. 请帮我。

Another solution to this problem is to hook into the ASP.NET pipeline using custom handlers to build a common response object. 解决此问题的另一种方法是使用自定义处理程序来建立公共响应对象,从而进入ASP.NET管道。 For instance: 例如:

[DataContract]
public class ApiResponse
{
  [DataMember]
  public string Version { get { return "1.2.3"; } }

  [DataMember]
  public int StatusCode { get; set; }

  [DataMember(EmitDefaultValue = false)]
  public string ErrorMessage { get; set; }

  [DataMember(EmitDefaultValue = false)]
  public object Result { get; set; }

  public ApiResponse(HttpStatusCode statusCode, object result = null, string   errorMessage = null)
  {
      StatusCode = (int)statusCode;
      Result = result;
      ErrorMessage = errorMessage;
  }
}

Have a look at this post for a reference implementation http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information 请参阅此帖子以获取参考实现http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM