所需的JSON错误响应模型与使用的类不匹配。
考虑重构类模型以服务于单个职责
public class ResponseData {
public List<AccountDTO> AccountList { set; get; }
public string ReturnMessage { set; get; }
}
还可以重构API操作,以根据操作流返回适当的响应。
[HttpGet]
public IHttpActionResult getAllAccounts(string BRN, string CompanyName) {
try {
ResponseData response = new ResponseData();
List<AccountDTO> accountlist = null;
IAccountInterface usecase = new AccountDAO();
if (BRN != null && CompanyName != null) {
accountlist = usecase.getAccountbyBRNCompanyName().Where(p => p.BRN.ToLower().Equals(BRN.ToLower()) && p.CompanyName.ToLower().Contains(CompanyName.ToLower())).ToList();
response.ReturnMessage = "Data filter by BRN and CompanyName.";
} else {
response.ReturnMessage = "Data filter cannot be null.";
}
response.AccountList = accountlist;
return Ok(response);
}
catch (Exception e) {
Console.WriteLine("Error: " + e.Message + ", Stack: " + e.StackTrace);
var response = new {
error = new {
code = "sample code",
message = e.Message,
innererror = new {
message = e.Message,
type = e.GetType().Name,
stacktrace = e.StackTrace
}
}
}
var responseMessage = Request.CreateResponse(HttpStatusCode.InternalServerError, response);
return ResponseMessage(responseMessage);
}
}