如何自定义WebAPI 2响应,如状态,数据,JSON格式的消息
成功请求:
{
"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"
}
答案 0 :(得分: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字符串。