【发布时间】:2017-04-01 09:30:27
【问题描述】:
我创建了 Web API,它接受四个输入参数,用于查询 Oracle 数据库并以 JSON 格式返回结果。现在,如果缺少任何输入参数或格式错误,我正在尝试处理 URI 中的任何异常。就像返回 JSON "error":"ROOM cannot be Empty or NULL" 如果 URI 中的 ROOM 是空的,比如 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;
}
使用我上面的代码,它确实返回 ROOM 不能为 Empty 或 NULL 如何得到 "error":"ROOM cannot be Empty or NULL"。还有什么方法可以处理 URLI 中的错误并将 JSON 响应返回为"error":"Poorly Formed URI"
【问题讨论】:
标签: c# asp.net json asp.net-web-api