Home > other >  How to handle "undefined" or "null" in ASP.NET Core web API from frontend React.
How to handle "undefined" or "null" in ASP.NET Core web API from frontend React.

Time:03-25

im in the process of writing ASP.NET Core REST API. here is controller method and this method should get selected when incoming route was matched.

controller.cs

[HttpGet]
        [Route("/api/Account/{accountID}/{productIds}/files")]
        public ActionResult<IEnumerable<FilesDto>> GetFiles(long accountID, string productIds)
        {
            using (new MethodCallLogger(logger, UserContext))
            {
                return Ok(FilesService.GetFiles(accountID, productIds));
            }
        }

FilesService.cs

public IEnumerable<FilesDto> GetFiles(long accountID, string productIds)
{
// in some cases productIds will come empty

if(!string.isNullorEmpty(productIds)
{

}
}

in some cases productIds will come empty, to select all the products.

if i pass null or empty string from FrontEnd Reactjs, here its receiving "null" or "undefined" as string value. so the string.isNullorEmpty condition get passed and throwing error, like invalid produtIDs.

so, what is the perfect to handle this "null" or "undefined". or how can we pass empty string or null from reactjs to backend.

Thanks for your time.

CodePudding user response:

Create a NotFoundApiException

public class NotFoundApiException : Exception
{
    public NotFoundApiException(string message) : base(message) { }

    public NotFoundApiException(string message, params object[] args)
        : base(String.Format(CultureInfo.CurrentCulture, message, args))
    {
    }
}

Create A Custom Error handling Middleware

public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception error)
        {
            var response = context.Response;
            response.ContentType = "application/json";
            
            string erorMessage = error.Message;

            switch (error)
            {

                case NotFoundApiException e:
                    // custom not-found application error
                    errorMessage = e.Message;
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    break;

                default:
                    // unhandled error
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
            }

            var result = JsonConvert.SerializeObject(new
            {
                message = errorMessage
            });

            await response.WriteAsync(result);
        }
    }
}

Then use the Middleware in Startup/Program.cs :

Then simply throw this exception when value is null by :


if(value is null)
    throw new NotFoundApiException("Data is null")

CodePudding user response:

You can use "all" in productIds for example:

/api/Account/55/all/files

Or you can also change the structure of the api for example:

/api/Account/files/{accountID}/{productIds}

And productIds can be "all" or Number

or you can use queryParams for productIds like:

/api/Account/{accountID}/files?productIds=Number

for example:

/api/Account/20/files?productIds=4

and when productIds not sended, you send all files for specific accountID

1./api/Account/20/files

Or

2./api/Account/20/files?productIds=all

  • Related