0

I have created the Web API that accepts four input parameters that is used in Querying Oracle Database and returns result in the JSON format. Now I am trying to handle any exception in the URI if there is any input parameter missing or in the wrong format . Like returning in JSON "error":"ROOM cannot be Empty or NULL" if the ROOM in URI is empty like ROOM=&DOB_GT=01-SEP-05&DOB_LT=30-DEC-06&STATUS_TYPE=CMPLT

public class TGSDataController : ApiController
{
[HttpGet]
public HttpResponseMessage Getdetails(string ROOM, DateTime DOB_GT, DateTime DOB_LT, string STATUS_TYPE)
{
    if (string.IsNullOrEmpty(ROOM))
    {
        var resp = new HttpResponseMessage()
        {
            Content = new StringContent("ROOM cannot be Empty or NULL")
        };
        resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        return resp;
    }
    List<OracleParameter> prms = new List<OracleParameter>();
    List<string> selectionStrings = new List<string>();
    prms.Add(new OracleParameter("ROOM", OracleDbType.Varchar2, ROOM, ParameterDirection.Input));
    prms.Add(new OracleParameter("DOB_GT", OracleDbType.Date, DOB_GT, ParameterDirection.Input));
    prms.Add(new OracleParameter("DOB_LT", OracleDbType.Date, DOB_LT, ParameterDirection.Input));
    prms.Add(new OracleParameter("STATUS_TYPE", OracleDbType.Varchar2, STATUS_TYPE, ParameterDirection.Input));

    string connStr = ConfigurationManager.ConnectionStrings["TGSDataBaseConnection"].ConnectionString;
    using (OracleConnection dbconn = new OracleConnection(connStr))
    {
        DataSet userDataset = new DataSet();
        var strQuery = "SELECT * from LIMS_SAMPLE_RESULTS_VW where ROOM = :ROOM and DOB > :DOB_GT and DOB < :DOB_LT and STATUS_TYPE= :STATUS_TYPE ";

        var returnObject = new { data = new OracleDataTableJsonResponse(connStr, strQuery, prms.ToArray()) };
        var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
        ContentDispositionHeaderValue contentDisposition = null;
        if (ContentDispositionHeaderValue.TryParse("inline; filename=TGSData.json", out contentDisposition))
        {
            response.Content.Headers.ContentDisposition = contentDisposition;
        }
        return response;
    }

With my code above it does return like ROOM cannot be Empty or NULL how to get like "error":"ROOM cannot be Empty or NULL". Also is there any way to handle error in the URLI and return the JSON response as "error":"Poorly Formed URI"

3 Answers 3

1

First of all WebAPI Can serialize any object to JSON automatically there is no need for you to manually try build the HttpResponseMessage.

By using

Content = new StringContent("ROOM cannot be Empty or NULL")`

You just add a normal string to the reponse body.

Instead use the Request.CreateResponse extension method to build an HttpResponseMessage with any object inside it serialized as JSON.

return Request.CreateResponse(HttpStatusCode.BadRequest,resp);

By default WebAPI Will Serialize the Response Either on XML or JSON depents on the request header. In order to force JSON serializing only add this to your Application_Start()

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Now about Exceptions. By default WebAPI will handle thrown exceptions by its own, and return the default error response.

If you want to Intercept this functionality and return your own custom response on exception you should implement an ExceptionFilterAttribute

    public class BALExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
     {
        base.OnException(actionExecutedContext);
        actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, new { error = actionExecutedContext.Exception.Message });
    }
}

And also add it in your application start

GlobalConfiguration.Configuration.Filters.Add(new BALExceptionFilterAttribute());

Finally if you have WebAPI 2.1 you can handle URL Errors with Global ExceptionHandling

Otherwise here are some related questions. custom-error-pages-for-non-existant-directory-file-web-api-not-controllers how-to-handle-webapi-error-404

Sign up to request clarification or add additional context in comments.

6 Comments

Should I add GlobalConfiguration.Configuration.Filters.Add(new BALExceptionFilterAttribute()); in the FilterConfig.cs under App_Start folder.
I haven't added it there. It just on my Global.asax Application_Start();
Both GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);GlobalConfiguration.Configuration.Filters.Add(new BALExceptionFilterAttribute()); should go in Application_Start() ?
Exactly. That way WebAPI configuration is altered upon application startup.
I added them and tried to run the application by giving invalid input for the date as http://localhost:46151/api/TGSData?ROOM=KOMP2&DOB_GT=01--05&DOB_LT=30-DEC-06&STATUS_TYPE=CMPLT like DOB_GT=01--05 it didnt return any JSON instead in the browser shows like HTTP 400 Bad Request The Web page cannot be found
|
0

You can easily build an anonymous type with the error(s) that you want to return.

if (string.IsNullOrEmpty(ROOM))
    {
        return this.Request.CreateResponse(
        HttpStatusCode.BadRequest,
        new { error= "ROOM cannot be empty or NULL" });
        resp.Content.Headers.ContentType = 
           new MediaTypeHeaderValue("application/json");
        return resp;
    }

3 Comments

Thanks Cam Bruce. I tried to add the try catch block. But I am trying to give an invalid input parameters like api/TGSData?ROOM=KOMP2&DOB_GT=01--05&DOB_LT=30-DEC-06&STATUS_TYPE=CMPLT The value DOB_GT is erroneous (01--05) it throws error in the HTTP 400 Bad Request The Web page cannot be found but it doesnot return those exception detail in JSON response
ahh, see updated response. if you're manually checking your parameters, you can easily build up an object to return what you need
Cam Bruce, Is there a way I can check the check if the DateTime has the valid inputs
0

The client that tries to access your web service will not receive a JSON-formatted error; rather, it will experience an error at the client. A poor URI will not the client reach the server, who is returning the JSON data.

That should answer your second question.

As to the first, you have two choices: you can manually build the JSON return, or, you can use a JSON library.

To do it by hand, you could use something like this:

    {"error":"ROOM cannot be Empty or NULL"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.