1

I have a very simple Web API with only GET controller. Inside the get controller, I am reading an XML file, converting that XML file into a JSON object and returning it.

public JObject Get()
{
    //Read XML
    XDocument xDoc = XDocument.Load(@"D:\myfile.xml");
    string jsonStr = JsonConvert.SerializeXNode(xDoc);
    JObject json = JObject.Parse(jsonStr);

    return json;              
}

I want to put the XML reading and JSON conversion lines into an exception handler and return 404 Error code (or any proper code for this situation) if the XML file cannot be opened (or any other exception occurs). But since my return type id JObject, I am not able to return a proper http respose, so how can I do that?

2
  • Instead of JObject you can return an ActionResult. In case you find it you will return a JsonResult, otherwise HttpNotFound
    – Kostis
    Commented Oct 8, 2018 at 14:04
  • As far as I know Action result is specifically for MVC and IHttpActionResult is more commonly used in web api. Commented Oct 8, 2018 at 14:24

1 Answer 1

3

You should change the return type of the Action Method to IHttpActionResult you can then do something like this

public IHttpActionResult Get()
{
    if (!File.Exists(@"D:\myfile.xml"))
        return NotFound();

    //Read XML
    XDocument xDoc = XDocument.Load(@"D:\myfile.xml");
    string jsonStr = JsonConvert.SerializeXNode(xDoc);
    JObject json = JObject.Parse(jsonStr);
    return Ok(json);
}

This should give you the flexibility you are after.

Quick Explanation of methods used

return OK(json) will return a successful (HTTP 200) response with the serialised json in the body.

return NotFound() will result in a failed request and a HTTP 404 result.

For an error you should ideally return a 5xx code, which can be achieved with return InternalServerError();

For more information on these and other helpers in the ApiController base class, check out the page on microsoft docs

3
  • I think it's important to mention what Ok() does and what the OP can user for a 404 message (as they specifically asked for it). Commented Oct 8, 2018 at 14:23
  • @StormMuller: I thought that 404 is the proper code in this situation but please suggest if I should return something else ( updated my question).
    – skm
    Commented Oct 8, 2018 at 14:48
  • Your question was clear. What I'm raising where is that the Ok() method returns a 200 status code and not a 404status code. Which may or may not be what you intend to do. But the answer has been updated to include the NotFound() method which is what you need for the 404 status code. Commented Oct 9, 2018 at 9:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.