我已經創建了接受在查詢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"
感謝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
ahh,請參閱如果你手動檢查你的參數,你可以很容易地建立一個對象,以返回你需要的東西 –
Cam Bruce,有沒有辦法檢查DateTime是否有有效的輸入 – trx