Звонок не передается от контроллера к модели в веб-интерфейсе - PullRequest
0 голосов
/ 31 августа 2018

Я совершенно новый в веб-API. Я создал веб-API просто для извлечения данных из базы данных Oracle с помощью нескольких статей, которые я нашел в Интернете. Я пытаюсь найти ошибку с утра, но пока безуспешно. Когда я пытаюсь запустить код, он не выдает никакой ошибки или чего-либо еще. Отладчик перешел на мой класс БД и останавливается. Ниже код моего контроллера.

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


namespace iLearnWebApi.Controllers
{
public class ValuesController : ApiController
{
    DAL.DBAccess dblayer = new DAL.DBAccess();
    public DataSet Getrecord(int programid)
    {            
        DataSet ds = dblayer.GetRecordbyid(programid);
        return ds;
    }
}   }

И ниже мой код DBClass.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Configuration;
using System.Data.Odbc;
using Oracle.ManagedDataAccess.Client;


namespace iLearnWebApi.DAL
{
 public class DBAccess
{
    OracleParameter[] _objOraParam;
    OracleConnection con = new OracleConnection();
    //--- Get Records By Program ID
    public DataSet GetRecordbyid(int progid)
    {            
        DataSet ds = new DataSet();
        try
        {
            _objOraParam = new OracleParameter[2];

            _objOraParam[0] = new OracleParameter("p_Program_ID", OracleDbType.Int32);
            _objOraParam[0].Direction = ParameterDirection.Input;
            _objOraParam[0].Value = progid;

            _objOraParam[1] = new OracleParameter("RCT_OUT", OracleDbType.RefCursor);
            _objOraParam[1].Direction = ParameterDirection.Output;

            ds = ExecuteDataset(con, CommandType.StoredProcedure, "ILS_USP_PROGRAM_DATA", _objOraParam);

        }
        catch (Exception ex)
        {
            LogError("GetRecordbyid", ex.Message.ToString());
            throw ex;
        }


        finally
        {
            con.Close();
        }
        return ds;
    }



    // Execute Data
    private DataSet ExecuteDataset(OracleConnection con, CommandType procname, string commandText, params OracleParameter[] objOraParam)
    {
        //create a command and prepare it for execution
        OracleCommand cmd = new OracleCommand();
        PrepareCommand(cmd, con, (OracleTransaction)null, procname, commandText, objOraParam);

        //create the DataAdapter & DataSet
        OracleDataAdapter da = new OracleDataAdapter(cmd);
        DataSet ds = new DataSet();

        //fill the DataSet using default values for DataTable names, etc.
        da.Fill(ds);
        cmd.Dispose();
        //return the dataset
        return ds;
    }


    //---- Used To Prepare Oracle command
    private void PrepareCommand(OracleCommand command, OracleConnection connection, OracleTransaction transaction, CommandType commandType, string commandText, OracleParameter[] commandParameters)
    {
        //if the provided connection is not open, we will open it
        string con_string = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;

        if (connection.State != ConnectionState.Open)
        {
            connection.ConnectionString = DecryptString(con_string, "CFSENC");
            connection.Open();
        }

        //associate the connection with the command
        command.Connection = connection;

        //set the command text (stored procedure name or Oracle statement)
        command.CommandText = commandText;

        //if we were provided a transaction, assign it.
        if (transaction != null)
        {
            command.Transaction = transaction;
        }

        //set the command type
        command.CommandType = commandType;

        //attach the command parameters if they are provided
        if (commandParameters != null)
        {
            AttachParameters(command, commandParameters);
        }

        return;
    }


    // Used For Attaching Parameter To Command
    private void AttachParameters(OracleCommand command, OracleParameter[] commandParameters)
    {
        foreach (OracleParameter p in commandParameters)
        {
            //check for derived output value with no value assigned
            if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
            {
                p.Value = DBNull.Value;
            }

            command.Parameters.Add(p);
        }
    }



    // Used For Decryption Of Encrypted String
    private string DecryptString(string con_string, string key)
    {
        byte[] plainBytes = null;
        try
        {

            string passWord = key;
            string strInput = con_string;

            byte[] encryptBytes = Convert.FromBase64String(strInput);
            MemoryStream ms = new MemoryStream(strInput.Length);
            //Using triple des for decryption
            TripleDESCryptoServiceProvider tDesCsp = new TripleDESCryptoServiceProvider();
            // Creating  decryption IV and Key using the key supplied by the user
            tDesCsp.IV = new byte[8];
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(passWord, new byte[0]);
            tDesCsp.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
            CryptoStream deEnStream = new CryptoStream(ms, tDesCsp.CreateDecryptor(), CryptoStreamMode.Write);
            //write the decrypted data to the stream
            deEnStream.Write(encryptBytes, 0, encryptBytes.Length);
            deEnStream.FlushFinalBlock();
            plainBytes = new byte[ms.Length];
            ms.Position = 0;
            //reading the decrypted stream and write it  into the byte array
            ms.Read(plainBytes, 0, (int)ms.Length);
            deEnStream.Close();
        }
        catch (Exception err)
        {
            string sErr = err.ToString();
            throw new Exception("Error decrypting string.");
        }
        return Encoding.UTF8.GetString(plainBytes);
    }


    // For Writing Log Files
    private void LogError(string header, string error)
    {
        string strPath;
        string strActualError;
        StreamWriter objErrWriter;
        DateTime objDt = DateTime.Now;
        string strDate;
        strDate = objDt.ToString("ddMMyyyy");

        try
        {
            // Get Actual Path of "Error" stored in Web.config
            strPath = ConfigurationManager.AppSettings["sPathErrorLog"];
            //Generates Path & LogFile Name of  ErrorLog
            strPath = strPath + strDate + ".log";
            // Generates Error Message
            strActualError = DateTime.Now + " : " + header + " : " + error;

            // Creation of File.
            objErrWriter = new StreamWriter(strPath, true, System.Text.Encoding.ASCII);

            objErrWriter.WriteLine("");
            objErrWriter.WriteLine(strActualError);
            objErrWriter.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
}}

Может кто-нибудь сказать мне, какую ошибку я совершил в приведенном выше коде.

1 Ответ

0 голосов
/ 31 августа 2018

Это звучит как проблема с маршрутизацией (без просмотра конфигурации вашего маршрута).

Попробуйте изменить: public DataSet Getrecord(int programid)

Кому: public DataSet Get(int id)

И звоните: localhost: 60908 / api / Значения / 1

...