2017-02-15 44 views
0

我怎樣才能定製的WebAPI像狀態,數據,消息JSON格式2響應像狀態定製的WebAPI響應,數據,消息甲酸

成功請求:

{ 
    "status": "success", 
    "data": { 
    /* Application-specific data would go here. */ 
    }, 
    "message": null /* Or optional success message */ 
} 

失敗請求:

{ 
    "status": "error", 
    "data": null, /* or optional error payload */ 
    "message": "Error xyz has occurred" 
} 

回答

1

定義一個新的類如:

public class ResponseDto 
{ 
    public string status { get; set; } 

    public dynamic data { get; set; } 

    public string message { get; set; } 
} 

然後填充具有各自的值的屬性和做:

var response = new ResponseDto() 
{ 
    response.status = " ", 
    response.data = obj, 
    response.message = " " 
} 

,然後從控制器方法(API),

return response; 

你的JSON格式器然後將轉換的響應對象轉換成JSON字符串。