2016-11-17 147 views
0

我已经创建了接受在查询Oracle数据库使用,并返回结果以JSON格式四个输入参数的网页API处理错误。现在我试图处理URI中的任何异常,如果有任何输入参数丢失或格式错误。像JSON "error":"ROOM cannot be Empty or NULL"返回,如果它上面没有返回样室不能为空或NULL如何得到像"error":"ROOM cannot be Empty or NULL"在URI房间是空喜欢ROOM=&DOB_GT=01-SEP-05&DOB_LT=30-DEC-06&STATUS_TYPE=CMPLT返回JSON时的Web API

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; 
    } 

我的代码。还有什么办法来处理URLI中的错误并返回JSON响应:"error":"Poorly Formed URI"

回答

1

您可以轻松地构建一个匿名类型与要返回错误(或多个)。

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; 
    } 
+0

感谢Cam Bruce。我尝试添加try catch块,但我试图给出一个无效的输入参数,比如'api/TGSData?ROOM = KOMP2&DOB_GT = 01--05&DOB_LT = 30-DEC-06&STATUS_TYPE = CMPLT'值DOB_GT错误(01--05)它在HTTP 400错误请求中抛出错误找不到Web页面,但它不会在JSON响应中返回那些异常细节 – trx

+0

ahh,请参阅如果你手动检查你的参数,你可以很容易地建立一个对象,以返回你需要的东西 –

+0

Cam Bruce,有没有办法检查DateTime是否有有效的输入 – trx

0

首先,WebAPI可以自动将任何对象序列化为JSON,不需要您手动尝试构建HttpResponseMessage。

通过使用

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

您只需添加一个普通的字符串的效应初探身体。

取而代之的是使用Request.CreateResponse扩展方法来构建一个HttpResponseMessage,并将其中的任何对象序列化为JSON。

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

默认情况下,WebAPI将序列化请求标头上的XML或JSON depents上的响应。 为了(),迫使JSON序列化只添加到您的的Application_Start现在

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

约例外。 默认的WebAPI将自行处理抛出的异常,并返回默认错误响应。

如果你想拦截此功能,并回报例外自己的自定义响应,你应该实现一个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 }); 
    } 
} 

,也可以添加在你的应用程序启动

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

最后,如果你的WebAPI 2.1可以处理URL错误与Global ExceptionHandling

否则,这里有一些相关的问题。 custom-error-pages-for-non-existant-directory-file-web-api-not-controllers how-to-handle-webapi-error-404

+0

我要补充'GlobalConfiguration.Configuration.Filters.Add(新BALExceptionFilterAttribute());'在App_Start文件夹下的FilterConfig.cs 。 – trx

+0

我还没有添加它。它只是在我的Global.asax Application_Start(); –

+0

'GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); GlobalConfiguration.Configuration.Filters.Add(new BALExceptionFilterAttribute());'应该在Application_Start()? – trx

0

试图访问您的Web服务的客户端不会收到JSON格式的错误;相反,它会在客户端遇到错误。一个糟糕的URI不会让客户端到达返回JSON数据的服务器。

这应该回答你的第二个问题。

对于第一个,您有两个选择:您可以手动构建JSON返回,或者,您可以使用JSON库。

用手做,你可以使用这样的事情:

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