简体   繁体   中英

C# - ASP.NET - REST API - Querying In Controller

I am attempting to follow this tutorial here:

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

To get a REST API set up for a website I am working on. I've never made anything with ASP.NET before so some stuff is throwing me off. I've made it to here (with changes in the models):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DashBoardWidgets.Models;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

namespace DashBoardWidgets.Controllers
{
    public class BoilerReadingsController : ApiController
    {
        public BoilerReading ExecuteQuery()
        {
            var MyBoilerReading = new BoilerReading();
            DataTable dt = new DataTable();
            SqlConnection connection = new SqlConnection("Data Source=.\\SQLExpress;Initial Catalog=DNN;User ID=sa;Password=*****;");
            connection.Open();
            SqlCommand sqlCmd = new SqlCommand("select top 1 * from DNN.dbo.avtActionForm_BoilerReadingsLog order by TimeStamp", connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                DateTime TimeStamp_q = (DateTime)dt.Rows[0]["TimeStamp"];
                int TurbineChosen_q = (int)dt.Rows[0]["TurbineChosen"];
                decimal MOPSuctionPressure_q = (decimal)dt.Rows[0]["MOPSuctionPressure"];
                decimal LubeOilPressure_q = (decimal)dt.Rows[0]["LubeOilPressure"];
                decimal ControlOilPressure_q = (decimal)dt.Rows[0]["ControlOilPressure"];
                decimal LubeOilTemp_q = (decimal)dt.Rows[0]["LubeOilTemp"];
                decimal BRNOilTemp1_q = (decimal)dt.Rows[0]["BRNOilTemp1"];
                decimal TBDRNOilTempFront_q = (decimal)dt.Rows[0]["TBDRNOilTempFront"];
                decimal TBDRNOilTempRear_q = (decimal)dt.Rows[0]["TBDRNOilTempRear"];
                decimal BRNOilTemp2_q = (decimal)dt.Rows[0]["BRNOilTemp2"];
                decimal BRNOilTemp3_q = (decimal)dt.Rows[0]["BRNOilTemp3"];
                decimal BRNOilTemp4_q = (decimal)dt.Rows[0]["BRNOilTemp4"];
                decimal BRNOilTemp5_q = (decimal)dt.Rows[0]["BRNOilTemp5"];
                decimal BRNOilTemp6_q = (decimal)dt.Rows[0]["BRNOilTemp6"];
                decimal BRNOilTemp7_q = (decimal)dt.Rows[0]["BRNOilTemp7"];
                decimal SealOilPressureExciteEnd_q = (decimal)dt.Rows[0]["SealOilPressureExciteEnd"];
                decimal SealOilPressureTurbineEnd_q = (decimal)dt.Rows[0]["SealOilPressureTurbineEnd"];
                string Username_q = dt.Rows[0]["Username"].ToString();
                int Index_q = (int)dt.Rows[0]["Index"];
                new BoilerReading { TimeStamp = TimeStamp_q, TurbineChosen = TurbineChosen_q, MOPSuctionPressure = MOPSuctionPressure_q, LubeOilTemp = LubeOilTemp_q, ControlOilPressure = ControlOilPressure_q, BRNOilTemp1 = BRNOilTemp1_q, TBDRNOilTempFront = TBDRNOilTempFront_q, TBDRNOilTempRear = TBDRNOilTempRear_q, BRNOilTemp2 = BRNOilTemp2_q, BRNOilTemp3 = BRNOilTemp3_q, BRNOilTemp4 = BRNOilTemp4_q, BRNOilTemp5 = BRNOilTemp5_q, BRNOilTemp6 = BRNOilTemp6_q, BRNOilTemp7 = BRNOilTemp7_q, SealOilPressureExciteEnd = SealOilPressureExciteEnd_q, SealOilPressureTurbineEnd = SealOilPressureTurbineEnd_q, Username = Username_q, Index = Index_q };
            }

            connection.Close();
            return BoilerReading;           
        }

        BoilerReading[] BoilerReadings = new BoilerReading[]
        {
            new BoilerReading { TimeStamp = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
         };

        public IEnumerable<BoilerReading> GetAllBoilerReadings()
        {
            return BoilerReadings;
        }

        public IHttpActionResult BoilerReading(int id)
        {
            var BoilerReading = BoilerReadings.FirstOrDefault((p) => p.Id == id);
            if (BoilerReading == null)
            {
                return NotFound();
            }
            return Ok(BoilerReading);
        }
    }
}

However, I want to replace the static arrays with the query I have in the ExecuteQuery() function, but I can't figure it out. I've tried a few different ways. I've tried adding the code to query directly into the array parts and changing the variables, but the compiler doesn't seem to like them there. Whenever I try calling ExecuteQuery(); and passing the queried data it doesn't work.

What is the proper way to replace these arrays with queried data so that it is dynamic?

With a dynamic query from a SQL server.

First, don't name your method the same as a class.

Second, you have a method that returns a BoilerReading , just call it.

public IHttpActionResult GetBoilerReading(int id)
{
     var BoilerReading = ExecuteQuery(); //you will probably want this to take an int parameter and add a WHERE clause to your query.
     if (BoilerReading == null)
     {
         return NotFound();
     }
     return Ok(BoilerReading);
 }

Now fix up ExecuteQuery so it actually returns a BoilerReading instance:

public BoilerReading ExecuteQuery()
{
    var MyBoilerReading = new BoilerReading();
    DataTable dt = new DataTable();
    SqlConnection connection = new SqlConnection("Data Source=.\\SQLExpress;Initial Catalog=DNN;User ID=sa;Password=*****;");
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand("select top 1 * from DNN.dbo.avtActionForm_BoilerReadingsLog order by TimeStamp", connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
    sqlDa.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        DateTime TimeStamp_q = (DateTime)dt.Rows[0]["TimeStamp"];
        int TurbineChosen_q = (int)dt.Rows[0]["TurbineChosen"];
        decimal MOPSuctionPressure_q = (decimal)dt.Rows[0]["MOPSuctionPressure"];
        decimal LubeOilPressure_q = (decimal)dt.Rows[0]["LubeOilPressure"];
        decimal ControlOilPressure_q = (decimal)dt.Rows[0]["ControlOilPressure"];
        .... etc.
        MyBoilerReading.Timestamp = TimeStamp_q;
        MyBoilerReading.TurbineChosen = TurbineChosen_q;
        ... etc.    
    }

    connection.Close();
    return MyBoilerReading; //return the instance that you actually populate with values.      
}

Note that I am not promoting this as good design. You will need more robust error and null checking. You are also using resources (Connections, Commands, etc.) that should be Disposed .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM