How to return a Json response from a service layer (Dot net core 3.1)

Viewed 166

I have a question. I have a dot net core 3.1 app. I have a appointment controller which calls a appointment service. The appointment calls a validation service to validate some values in de database. I want to stop the execution if the value doesn't exists in the database. I want to return a list of response to the client from the validation service.

How can i a return a response from the validation service?

code example:

public async Task<bool> Validate() { 
bool ValidateOK = await 
_validateService.ValidateObjects(ObjectsToValidate); 
if (ValidateOK == false) //Throw list of Errors en messages return true; 
}
Responses wil be like this
{
   Errorcode: 201
   ErrorMessage: Value1 doesn't exists in the database
}
{
   Errorcode: 201
   ErrorMessage: Value2 doesn't exists in the database
}
1 Answers

To return a Json response you should change the return Type of the function/ method used as the endpoint. This is the first function that gets called by the front-end.

I'd recommend creating a custom class in this case. This will make it easy to implement more specific handling of the response. And will make it more accessible for different parts of your application.

The class would look like this (you can manipulate it to fit your needs):

public class Response
{
    public int StatusCode { get; set; }
    public string Message { get; set; }
}

Your Validate function should look like this:

public async Task<Response> Validate(type objectToValidate)
{
    // validation process
    if (!validated) return response;
}

Don't forget to set the Type in the parameters to whatever you need to validate. Your Validate function is not responsible for talking to the front-end. So you wouldn't want it to return Json.

Your Endpoint will look like this:

public async Task<JsonResult> MyEndpoint()
{
    // your code
    var response = await _validateService.Validate(objectToValidate);
    return Json(response);
}

You might need to reference Microsoft.AspNetCore.Mvc.

Related