Answer the question
In order to leave comments, you need to log in
How to make a single response format for all api requests in asp.net core mvc?
Before, I used DelegatingHandler, and I could wrap all the responses from action into a beautiful object (with a status code, an error message and a result object ...). But I don’t understand how to implement this in the new asp.net (( Please tell me
Answer the question
In order to leave comments, you need to log in
More or less like this:
public class APIResult
{
public int errorCode { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string errorMessage { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public object messageData { get; set; }
public APIResult(int errorCode, string errorMessage, object data)
{
this.errorCode = errorCode;
this.errorMessage = errorMessage;
messageData = data;
}
}
public abstract class BaseAPIController : Controller
{
protected JsonResult ApiMessage(int errorCode, string errorMessage = null, object data = null)
{
return Json(new APIResult(errorCode, errorMessage, data));
}
}
// И пример иÑпользованиÑ
public YourController: BaseAPIController
{
public async Task<IActionResult> YourAction(int id)
{
return ApiMessage(0, data: new { id = id });
// Или
// return ApiMessage(-2, errorMessage: "Invalid request parameters");
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question