Web API获取输入参数以查询Oracle数据库

时间:2016-11-16 17:24:30

标签: c# asp.net oracle asp.net-web-api

我正在使用四个输入参数创建Web API。输入参数将在Select语句的where子句中使用.Oracle中的字段为ROOM (Varchar),SUBMIT_DATE(Date)(eg:01-JAN-16)。 URL应该是`/ api / TGSSampleDatas?Room = 654& SUBMITDATE = '01 -Jan-16'。所以在C#中,我使用Get操作创建Controller,如

public class TGSSampleDatasController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Getdetails(string ROOM,DateTime ? SUBMITDATE = null)
        {
            List<OracleParameter> prms = new List<OracleParameter>();
            List<string> selectionStrings = new List<string>();
            string connStr = ConfigurationManager.ConnectionStrings["TGSDataConnection"].ConnectionString;
        using (OracleConnection dbconn = new OracleConnection(connStr))
        {
            DataSet userDataset = new DataSet();
            var strQuery = "SELECT * from LIMS_SAMPLE_RESULTS_VW where ROOM = " + ROOM +"and SUBMIT_DATE =" +"'"+SUBMITDATE+"'";
           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;

在小提琴手中获得以下错误 {"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'SUBMITDATE' of non-nullable type 'System.DateTime' for method 'System.Net.Http.HttpResponseMessage Getdetails(System.String, System.DateTime)' in 'TGSSampleData.Controllers.TGSSampleDatasController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."} enter image description here

1 个答案:

答案 0 :(得分:1)

您的Sql语句错误。

"SELECT * from LIMS_SAMPLE_RESULTS_VW where ROOM = " + ROOM +"and SUBMIT_DATE =" +"'"+SUBMITDATE+"'";
//--------------------------------no ticks-^----^ -no space--^
  • Room是一个字符串,所以如果你要使用字符串连接(但不要&#39; T ),你应该用'括起来,否则它就成了声明的一部分。
  • ROOM与and之间也没有空格。

真正的解决方法是使用ROOMSUBMITDATE的参数。这样做可以防止这样的问题开始发生。

我猜测参数类型,您可能需要纠正它们。

List<OracleParameter> prms = new List<OracleParameter>();
prms.Add(new OracleParameter("ROOM", OracleDbType.Varchar2, ROOM, ParameterDirection.Input));
prms.Add(new OracleParameter("SUBMITDATE", OracleDbType.Date, SUBMITDATE ?? System.DBNull.Value, ParameterDirection.Input));
// note that because you are using a nullable type as input you should pass in DBNull.Value as the value if the value is null in your c# code.

var strQuery = "SELECT * from LIMS_SAMPLE_RESULTS_VW where ROOM = :ROOM and SUBMIT_DATE = :SUBMITDATE";

您正在执行的字符串连接会使您的系统容易受到SQL注入攻击,并且会给您的sql代码带来问题。后者可以通过传入包含'标记的值来说明。再做一次,你可以结束sql语句并在最后添加另一个。