简体   繁体   中英

How to return proper Http Response instead of JSON object

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM