Search code examples
c#jsonapihttp-postjsonresult

How to return a error message in json result in C#?


This is my code:

    [HttpPost]
    [Route("api/bulkUpload")]
    [IgnoreAntiforgeryToken]
    public JsonResult bulkUpload(IFormFile file)
    {
        List<Input> inputs = new List<Input>();
        try
        {
            var extension = Path.GetExtension(file.FileName);
            if (extension == ".csv")
            {
              .
              .
              .
            }
        }
        catch(exception ex)
        {
          return json(new { errormessage ="invalid file extension"});
        }
     return jsonresult(inputs)
    }

In swagger api if I give a different file(diff extensions) like .txt or .xls it is giving error code:500. But I want to return a error message as invalid file extension. PLease help on this code.


Solution

  • This may depend a bit on what version of ASP.NET you are using, but you should be able to do something like:

    [Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
    
        [Microsoft.AspNetCore.Mvc.HttpPost]
        [Microsoft.AspNetCore.Mvc.Route("api/bulkUpload")]
        [IgnoreAntiforgeryToken]
        public IActionResult bulkUpload(IFormFile file)
        {
            List<Input> inputs = new List<Input>();
            try
            {
                var extension = Path.GetExtension(file.FileName);
                if (extension == ".csv")
                {
                    // do the thing!
                }
            }
            catch (Exception ex)
            {
                return BadRequest("invalid file extension");
                // or try this:
                // return BadRequest(new JsonResult("invalid file extension"));
            }
    
            return new JsonResult("ok");
        }
    
    }
    
    public class Input
    {
    
    }
    

    Here is the docs on it and some examples.