2016-11-17 149 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"}