首页 > 代码库 > 2、设计Web Api分层架构

2、设计Web Api分层架构

一、创建Model层

  技术分享

技术分享
using System;

namespace SCM.API.MODEL
{
    public partial class USR_MSTR
    {
        public string USR_USER { get; set; }
        public string USR_NAME { get; set; }
        public string USR_GROUP { get; set; }
        public string USR_DEPT { get; set; }
        public string USR_PASSWORD { get; set; }
        public string USR_LIB_PATH { get; set; }
        public string USR_DEF_SITE { get; set; }
        public Nullable<int> USR_WARNING_CIRCLE { get; set; }
        public Nullable<short> USR_EMPLOYEE { get; set; }
        public Nullable<short> USR_LOCK { get; set; }
        public Nullable<short> USR_OUT { get; set; }
        public string USR_AGENT { get; set; }
        public string USR_ALLOW_IP { get; set; }
        public string USR_CRT_BY { get; set; }
        public Nullable<System.DateTime> USR_CRT_DATE { get; set; }
        public string USR_POSITION { get; set; }
        public string USR_MOBILE { get; set; }
        public string USR_BQQ { get; set; }
        public string USR_VIEW_SITES { get; set; }
        public string USR_RMKS { get; set; }
        public string USR_CHAR1 { get; set; }
        public string USR_CHAR2 { get; set; }
        public string USR_CHAR3 { get; set; }
        public string USR_CHAR4 { get; set; }
        public string USR_CHAR5 { get; set; }
        public string USR_CHAR6 { get; set; }
        public Nullable<decimal> USR_QTY1 { get; set; }
        public Nullable<decimal> USR_QTY2 { get; set; }
    }
}
View Code
二、创建Common工具类
技术分享
//加密解密
using System;
using System.Security.Cryptography;
using System.Text;

namespace SCM.API.Common
{
    public class DESEncrypt
    {
        public DESEncrypt()
        { 
        
        }
        
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "MATICSOFT");
        }
        #region 加密
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] InputByteArray;
            InputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey,"md5").Substring(0,8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(InputByteArray, 0, InputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}",b);
            }
            return ret.ToString();
        }
        #endregion

        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "MATICSOFT");
        }

        #region 解密
        /// <summary>
        /// 解密操作
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int Len;
            Len = Text.Length / 2;
            byte[] inputByteArray = new byte[Len];
            int x, i;
            for (x = 0; x < Len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
        #endregion
    }
}
View Code 加密解密
技术分享
using System.Configuration;

namespace SCM.API.Common
{
    public class GetConnString
    {
        /// <summary>
        /// 获取深圳ERP连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                string _connectionString = ConfigurationManager.AppSettings["szErpConnString"];
                string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"];
                if (ConStringEncrypt == "true")
                {
                    //_connectionString = DESEncrypt.Decrypt(_connectionString);//加密
                }
                return _connectionString;
            }
        }

        /// <summary>
        /// 得到web.config里配置项的数据库连接字符串。
        /// </summary>
        /// <param name="configName"></param>
        /// <returns></returns>
        public static string GetConnectionString(string configName)
        {
            string connectionString = ConfigurationManager.AppSettings[configName];
            string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"];
            if (ConStringEncrypt == "true")
            {
                //connectionString = DESEncrypt.Decrypt(connectionString);
            }
            return connectionString;
        }
    }
}
View Code GetConnectionString
技术分享
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;

namespace SCM.API.Common
{
    public class OracleHelper
    {
        //数据库连接字符串(web.config来配置),多数据库可使用DbHelperSQLP来实现.
        private static string connectionString = GetConnString.ConnectionString;
        public OracleHelper()
        { 
           
        }

        #region 公用方法
        /// <summary>
        /// 判断是否存在某表的某个字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="columnName">列名称</param>
        /// <returns>是否存在</returns>
        public static bool ColumnExists(string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id(‘" + tableName + "‘) and [name]=‘" + columnName + "";
            object res = GetSingle(sql);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }

        /// <summary>
        /// 获取最大值max
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        /// <summary>
        /// 检验SQL有效性
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 表是否存在
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool TabExists(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N‘[" + TableName + "]‘) and OBJECTPROPERTY(id, N‘IsUserTable‘) = 1";
            //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N‘[dbo].[" + TableName + "]‘) AND type in (N‘U‘)";
            object obj = GetSingle(strsql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 校验空值
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static bool Exists(string strSql, params OracleParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.OracleClient.OracleException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public static int ExecuteSqlByTime(string SQLString, int Times)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.OracleClient.OracleException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
      
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>        
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (OracleConnection conn = new OracleConnection(connectionString))
            {
                conn.Open();
                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                OracleTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string content)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand(SQLString, connection);
                System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter(":content", OracleType.LongVarChar);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.OracleClient.OracleException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static object ExecuteSqlGet(string SQLString, string content)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand(SQLString, connection);
                System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter("@content", SqlDbType.NText);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (System.Data.OracleClient.OracleException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand(strSQL, connection);
                System.Data.OracleClient.OracleParameter myParameter = new System.Data.OracleClient.OracleParameter(":fs", OracleType.Blob);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.OracleClient.OracleException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.OracleClient.OracleException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        public static object GetSingle(string SQLString, int Times)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.OracleClient.OracleException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        /// <summary>
        /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对OracleDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>OracleDataReader</returns>
        public static OracleDataReader ExecuteReader(string strSQL)
        {
            OracleConnection connection = new OracleConnection(connectionString);
            OracleCommand cmd = new OracleCommand(strSQL, connection);
            try
            {
                connection.Open();
                OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (System.Data.OracleClient.OracleException e)
            {
                throw e;
            }   

        }
        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    OracleDataAdapter command = new OracleDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.OracleClient.OracleException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        public static DataSet Query(string SQLString, int Times)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    OracleDataAdapter command = new OracleDataAdapter(SQLString, connection);
                    command.SelectCommand.CommandTimeout = Times;
                    command.Fill(ds, "ds");
                }
                catch (System.Data.OracleClient.OracleException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }



        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.OracleClient.OracleException e)
                    {
                        throw e;
                    }
                }
            }
        }


        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param>
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (OracleConnection conn = new OracleConnection(connectionString))
            {
                conn.Open();
                using (OracleTransaction trans = conn.BeginTransaction())
                {
                    OracleCommand cmd = new OracleCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            OracleParameter[] cmdParms = (OracleParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param>
        //public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
        //{
        //    using (OracleConnection conn = new OracleConnection(connectionString))
        //    {
        //        conn.Open();
        //        using (OracleTransaction trans = conn.BeginTransaction())
        //        {
        //            OracleCommand cmd = new OracleCommand();
        //            try
        //            { int count = 0;
        //                //循环
        //                foreach (CommandInfo myDE in cmdList)
        //                {
        //                    string cmdText = myDE.CommandText;
        //                    OracleParameter[] cmdParms = (OracleParameter[])myDE.Parameters;
        //                    PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                           
        //                    if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
        //                    {
        //                        if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
        //                        {
        //                            trans.Rollback();
        //                            return 0;
        //                        }

        //                        object obj = cmd.ExecuteScalar();
        //                        bool isHave = false;
        //                        if (obj == null && obj == DBNull.Value)
        //                        {
        //                            isHave = false;
        //                        }
        //                        isHave = Convert.ToInt32(obj) > 0;

        //                        if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
        //                        {
        //                            trans.Rollback();
        //                            return 0;
        //                        }
        //                        if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
        //                        {
        //                            trans.Rollback();
        //                            return 0;
        //                        }
        //                        continue;
        //                    }
        //                    int val = cmd.ExecuteNonQuery();
        //                    count += val;
        //                    if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
        //                    {
        //                        trans.Rollback();
        //                        return 0;
        //                    }
        //                    cmd.Parameters.Clear();
        //                }
        //                trans.Commit();
        //                return count;
        //            }
        //            catch
        //            {
        //                trans.Rollback();
        //                throw;
        //            }
        //        }
        //    }
        //}
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param>
        //public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
        //{
        //    using (OracleConnection conn = new OracleConnection(connectionString))
        //    {
        //        conn.Open();
        //        using (OracleTransaction trans = conn.BeginTransaction())
        //        {
        //            OracleCommand cmd = new OracleCommand();
        //            try
        //            {
        //                int indentity = 0;
        //                //循环
        //                foreach (CommandInfo myDE in SQLStringList)
        //                {
        //                    string cmdText = myDE.CommandText;
        //                    OracleParameter[] cmdParms = (OracleParameter[])myDE.Parameters;
        //                    foreach (OracleParameter q in cmdParms)
        //                    {
        //                        if (q.Direction == ParameterDirection.InputOutput)
        //                        {
        //                            q.Value = http://www.mamicode.com/indentity;>//                        }
        //                    }
        //                    PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
        //                    int val = cmd.ExecuteNonQuery();
        //                    foreach (OracleParameter q in cmdParms)
        //                    {
        //                        if (q.Direction == ParameterDirection.Output)
        //                        {
        //                            indentity = Convert.ToInt32(q.Value);
        //                        }
        //                    }
        //                    cmd.Parameters.Clear();
        //                }
        //                trans.Commit();
        //            }
        //            catch
        //            {
        //                trans.Rollback();
        //                throw;
        //            }
        //        }
        //    }
        //}
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param>
        public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
        {
            using (OracleConnection conn = new OracleConnection(connectionString))
            {
                conn.Open();
                using (OracleTransaction trans = conn.BeginTransaction())
                {
                    OracleCommand cmd = new OracleCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            OracleParameter[] cmdParms = (OracleParameter[])myDE.Value;
                            foreach (OracleParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (OracleParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString, params OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.OracleClient.OracleException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对OracleDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>OracleDataReader</returns>
        public static OracleDataReader ExecuteReader(string SQLString, params OracleParameter[] cmdParms)
        {
            OracleConnection connection = new OracleConnection(connectionString);
            OracleCommand cmd = new OracleCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.OracleClient.OracleException e)
            {
                throw e;
            }
            //            finally
            //            {
            //                cmd.Dispose();
            //                connection.Close();
            //            }    

        }

        /// <summary>
        /// 执行查询语句,返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataTable  DtQuery(string SQLString, params OracleParameter[] cmdParms)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (OracleDataAdapter da = new OracleDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        da.Fill(dt);
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.OracleClient.OracleException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return dt;
                }
            }
        }

        /// <summary>
        /// 返回表集
        /// </summary>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public static DataTable DtQuery(string SQLString)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                OracleCommand cmd = new OracleCommand(SQLString, connection);
                using (OracleDataAdapter da = new OracleDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        da.Fill(dt);
                    }
                    catch (System.Data.OracleClient.OracleException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return dt;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        /// <param name="cmdText"></param>
        /// <param name="cmdParms"></param>
        private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string cmdText, OracleParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (OracleParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);

                }
            }
        }

        #endregion

        #region 存储过程操作

        /// <summary>
        /// 执行存储过程,返回OracleDataReader ( 注意:调用该方法后,一定要对OracleDataReader进行Close )
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleDataReader</returns>
        public static OracleDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            OracleConnection connection = new OracleConnection(connectionString);
            OracleDataReader returnReader;
            connection.Open();
            OracleCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
            return returnReader;
            
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                OracleDataAdapter sqlDA = new OracleDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                OracleDataAdapter sqlDA = new OracleDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.SelectCommand.CommandTimeout = Times;
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }


        /// <summary>
        /// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleCommand</returns>
        private static OracleCommand BuildQueryCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            OracleCommand command = new OracleCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (OracleParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }

        /// <summary>
        /// 执行存储过程,返回影响的行数        
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                int result;
                connection.Open();
                OracleCommand command = BuildIntCommand(connection, storedProcName, parameters);
                rowsAffected = command.ExecuteNonQuery();
                result = (int)command.Parameters["ReturnValue"].Value;
                //Connection.Close();
                return result;
            }
        }

        public static Dictionary<string, object> RunProcedureDic(string storeProcName, IDataParameter[] parameters, Dictionary<string,object> dic)
        {
            using (OracleConnection connection = new OracleConnection(connectionString))
            {
                connection.Open();
                OracleCommand command = BuildQueryCommand(connection, storeProcName, parameters);
                OracleParameter out_flag = command.Parameters.Add("var_flag", OracleType.Number);
                out_flag.Direction = ParameterDirection.Output;
                OracleParameter out_msg = command.Parameters.Add("var_msg", OracleType.VarChar,4000);
                out_msg.Direction = ParameterDirection.Output;
                out_msg.Size = 4000;
                command.ExecuteNonQuery();
                dic.Add("var_flag",out_flag.Value);
                dic.Add("var_msg", out_msg.Value);
                return dic;
            }
        }
        /// <summary>
        /// 创建 OracleCommand 对象实例(用来返回一个整数值)    
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleCommand 对象实例</returns>
        private static OracleCommand BuildIntCommand(OracleConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            OracleCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new OracleParameter("ReturnValue",
                OracleType.Int32, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }
        #endregion



    }
}
View Code OracleHelper
技术分享
namespace SCM.API.Common
{
    /// <summary>
    /// Request请求帮助类
    /// </summary>
    public class RequestHelper
    {
        /// <summary>
        /// Post提交
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultVal"></param>
        /// <returns></returns>
        public string GetRequsetForm(string key, string defaultVal)
        {
            if (System.Web.HttpContext.Current.Request.Form[key] == null)
                return defaultVal;
            return System.Web.HttpContext.Current.Request.Form[key].ToString();
        }

        /// <summary>
        /// Get提交
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultVal"></param>
        /// <returns></returns>
        public string GetRequsetQueryString(string key, string defaultVal)
        {
            if (System.Web.HttpContext.Current.Request.QueryString[key] == null)
                return defaultVal;
            return System.Web.HttpContext.Current.Request.QueryString[key].ToString();
        }
    }
}
View Code RequestHelper
技术分享
namespace SCM.API.Common
{
    public class ReturnJsonResult
    {
        public static JsonResult<T> GetJsonResult<T>(int code, string msg, T data)
        {
            JsonResult<T> jsonResult = new JsonResult<T>();
            jsonResult.code = code;
            jsonResult.msg = msg;
            jsonResult.data = data;
            return jsonResult;
        }
    }

    /// <summary>
    /// 定义统计返回json格式数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class JsonResult<T>
    {
        public int code { get; set; }
        public string msg { get; set; }
        public T data { get; set; }
    }
}
View Code ReturnJsonResult
技术分享
using System.Data;
using System.Data.OracleClient;

namespace SCM.API.Common
{
    public class WebConfigHelper
    {
        public static string ApiAuthorize { get; set; }
        public static string IPs { get; set; }
        public static string Macs { get; set; }

        public WebConfigHelper()
        {
            string sql = @"select * from api_mstr";
            using (OracleConnection conn = new OracleConnection(GetConnString.ConnectionString))
            {
                conn.Open();
                OracleCommand cmd = new OracleCommand(sql, conn);
                OracleDataAdapter myda = new OracleDataAdapter(cmd);
                DataTable dt = new DataTable();
                myda.Fill(dt);
                ApiAuthorize = "[";
                for (int i = 0; i <= dt.Rows.Count - 1; i++)
                {
                    ApiAuthorize += "{api_usr_user :‘" + dt.Rows[i]["api_usr_user"].ToString()+"‘,";
                    ApiAuthorize += "api_key :‘" + dt.Rows[i]["api_key"].ToString() + "‘},";
                    IPs += dt.Rows[i]["api_ip"].ToString() + ",";
                    Macs += dt.Rows[i]["api_mac"].ToString() + ",";
                }
                IPs = IPs.Substring(0, IPs.Length - 1);
                Macs = Macs.Substring(0, Macs.Length - 1);
                ApiAuthorize = ApiAuthorize.Substring(0, ApiAuthorize.Length - 1);
                ApiAuthorize += "]";
                myda.Dispose();
            }
        }
    }
}
View Code WebConfigHelper
三、创建Dal数据访问层
技术分享
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using SCM.API.Common;
using SCM.API.MODEL;

namespace SCM.API.DAL
{
    public class USR_MSTR_DAL
    {
        public USR_MSTR_DAL()
        {

        }

        /// <summary>
        /// 获取User列表
        /// </summary>
        /// <returns></returns>
        public DataTable GetUser()
        {
            String sql = @"select * from usr_mstr";
            DataTable dt = (DataTable)OracleHelper.GetSingle(sql);
            return dt;
        }

        /// <summary>
        /// 新增数据(删除、修改数据类似)
        /// </summary>
        /// <param name="USR_MSTR">实体类</param>
        /// <returns></returns>
        public int InsertUser(USR_MSTR usr_mstr)
        {
            String sql = @"insert into usr_mstr(usr_user,usr_name,usr_password,usr_dept,usr_group)
                         values
                         (:usr_user,:usr_name,:usr_password,:usr_dept,:usr_group)
                        ";
            OracleParameter[] pars = {
                 new OracleParameter(":usr_user",OracleType.VarChar),
                 new OracleParameter(":usr_name",OracleType.VarChar),
                 new OracleParameter(":usr_password",OracleType.VarChar),
                 new OracleParameter(":usr_dept",OracleType.VarChar),
                 new OracleParameter(":usr_group",OracleType.VarChar)};
            pars[0].Value =http://www.mamicode.com/ usr_mstr.USR_USER;
            pars[1].Value =http://www.mamicode.com/ usr_mstr.USR_NAME;
            pars[2].Value =http://www.mamicode.com/ usr_mstr.USR_PASSWORD;
            pars[3].Value =http://www.mamicode.com/ usr_mstr.USR_DEPT;
            pars[4].Value =http://www.mamicode.com/ usr_mstr.USR_GROUP;
            object ob = OracleHelper.GetSingle(sql, pars);
            if (ob == null)
                return 0;
            else
                return 1;
        }

        /// <summary>
        /// 返回行集
        /// </summary>
        /// <param name="USR_MSTR"></param>
        /// <returns></returns>
        public USR_MSTR GetUserReader(USR_MSTR usr_mstr)
        {
            DataTable dt = new DataTable();
            String sql = @"select * from usr_mstr where usr_user = :usr_user";
            OracleParameter[] pars = {
                                         new OracleParameter(":usr_user", OracleType.VarChar)};
            pars[0].Value =http://www.mamicode.com/ usr_mstr.USR_USER;
            OracleDataReader dr = OracleHelper.ExecuteReader(sql, pars);
            USR_MSTR userinfo = new USR_MSTR();
            if (dr.Read())
            {
                userinfo.USR_USER = dr["usr_user"].ToString();
                userinfo.USR_NAME = dr["usr_name"].ToString();
                userinfo.USR_DEPT = dr["usr_dept"].ToString();
                userinfo.USR_GROUP = dr["usr_group"].ToString();
                dr.Close();
                return userinfo;
            }
            else
            {
                dr.Close();
                return null;
            }
        }

        public Dictionary<string, object> RunProcName(string sql, OracleParameter[] pars,Dictionary<string,object> dic)
        {
            return OracleHelper.RunProcedureDic(sql, pars, dic );
        }

    }
}
View Code USR_MSTR_DAL
四、创建BLL业务逻辑层
技术分享
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;

namespace SCM.API.IBLL
{
    public interface IUSER_MSTR
    {
        /// <summary>
        /// 获取User列表
        /// </summary>
        /// <returns></returns>
        DataTable GetUser();

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="USR_MSTR"></param>
        /// <returns></returns>
        int InsertUser(SCM.API.MODEL.USR_MSTR usr_mstr);

        /// <summary>
        /// 获取User行集
        /// </summary>
        /// <param name="USR_MSTR"></param>
        /// <returns></returns>
        SCM.API.MODEL.USR_MSTR GetUserReader(SCM.API.MODEL.USR_MSTR usr_mstr);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pars"></param>
        /// <param name="rowsAffected"></param>
        /// <returns></returns>
        Dictionary<string, object> RunProcName(string sql, OracleParameter[] pars, Dictionary<string,object> dic);
    }
}
View Code IUSR_MSTR
技术分享
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using SCM.API.DAL;
using SCM.API.IBLL;

namespace SCM.API.BLL
{
    public class USER_MSTR : IUSER_MSTR
    {
        SCM.API.DAL.USR_MSTR_DAL usr_mstr = new USR_MSTR_DAL();
        public DataTable GetUser()
        {
            return usr_mstr.GetUser();
        }

        public int InsertUser(SCM.API.MODEL.USR_MSTR _usr_mstr)
        {
            return usr_mstr.InsertUser(_usr_mstr);
        }

        public SCM.API.MODEL.USR_MSTR GetUserReader(SCM.API.MODEL.USR_MSTR _usr_mstr)
        {
            return usr_mstr.GetUserReader(_usr_mstr);
        }

        public Dictionary<string, object> RunProcName(string sql, OracleParameter[] pars, Dictionary<string,object> dic)
        {
            return usr_mstr.RunProcName(sql, pars, dic);
        }
    }
}
View Code USR_MSTR_BLL
五、UI
技术分享
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Web.Http;
using SCM.API.BLL;
using SCM.API.Common;

namespace SCM.API
{
    public class UserInfoController : ApiController
    {
        [HttpPost]
        public IHttpActionResult PostUser()
        {
            if (APIAuthorizeInfoValidate.ValidateApi("ERP012", "c3V5YW5qaWFuZw=="))
                return Ok(ReturnJsonResult.GetJsonResult(-1, "身份验证失败!", ""));
            return Ok(ReturnJsonResult.GetJsonResult(-1, "身份验证失败!", APIAuthorizeInfoValidate.GetWebClientIp()));
        }

        [HttpGet]
        public IHttpActionResult GetUserReader([FromUri] MODEL.USR_MSTR usr_mstr)
        {
            try
            {
                if (String.IsNullOrWhiteSpace(usr_mstr.API_USR_USER))
                {
                    return Ok(ReturnJsonResult.GetJsonResult(-1, "参数不能为空!(ApiUser)", ""));
                }
                else if (String.IsNullOrWhiteSpace(usr_mstr.API_KEY))
                {
                    return Ok(ReturnJsonResult.GetJsonResult(-1, "参数不能为空!(Key)", ""));
                }
                else if (string.IsNullOrWhiteSpace(usr_mstr.USR_USER))
                {
                    return Ok(ReturnJsonResult.GetJsonResult(-1, "参数不能为空!(User)", ""));
                }
                else if (!APIAuthorizeInfoValidate.ValidateApi(usr_mstr.API_USR_USER, usr_mstr.API_KEY))
                {
                    return Ok(ReturnJsonResult.GetJsonResult(-1, "身份验证失败!", ""));
                }

                SCM.API.MODEL.USR_MSTR UserInfo = new MODEL.USR_MSTR();
                UserInfo.USR_USER = usr_mstr.USR_USER;
                BLL.USER_MSTR func = new USER_MSTR();
                UserInfo = func.GetUserReader(UserInfo);

                return Ok(ReturnJsonResult.GetJsonResult(1, "", UserInfo));
            }
            catch
            {
                return Ok(ReturnJsonResult.GetJsonResult(0, "系统异常!", ""));
            }
        }

        /// <summary>
        /// 审核过账
        /// </summary>
        /// <param name="dn">实体参数</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult RunStoreProcedure([FromBody]USER_MSTR _usr_mstr)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            BLL.USER_MSTR fun = new USER_MSTR();
            string sql = "Test_pst";
            OracleParameter[] pars = { 
                                     new OracleParameter("var_usr_user",OracleType.VarChar),
                                     new OracleParameter("var_sign",OracleType.Int32),
                                     new OracleParameter("var_user",OracleType.VarChar)
                                     };
            pars[0].Value =http://www.mamicode.com/ dn.usr_user;
            pars[0].Direction = ParameterDirection.Input;
            pars[1].Value = http://www.mamicode.com/0;
            pars[1].Direction = ParameterDirection.Input;
            pars[2].Value =http://www.mamicode.com/ dn.usr_user;
            pars[2].Direction = ParameterDirection.Input;
            return Ok(ReturnJsonResult.GetJsonResult(1, "", fun.RunProcName(sql, pars, dic)));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strQuery"></param>
        /// <returns></returns>
        [HttpGet] //[FromUri]
        public IHttpActionResult HttpGetUser([FromUri]string strQuery)
        {
            MODEL.USR_MSTR usr_user = Newtonsoft.Json.JsonConvert.DeserializeObject<MODEL.USR_MSTR>(strQuery);
            return Ok(ReturnJsonResult.GetJsonResult(1, "HttpGet测试成功!", usr_user.USR_USER + "/" + usr_user.USR_NAME + "/" + usr_user.USR_DEPT));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="usr_user"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult HttpPostUser([FromBody]MODEL.USR_MSTR usr_user)
        {
            return Ok(ReturnJsonResult.GetJsonResult(1, "HttpPost测试成功!", usr_user.USR_USER + "/" + usr_user.USR_NAME + "/" + usr_user.USR_DEPT));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="usr_user"></param>
        /// <returns></returns>
        [HttpPut]
        public IHttpActionResult HttpPutUser([FromBody]MODEL.USR_MSTR usr_user)
        {
            return Ok(ReturnJsonResult.GetJsonResult(1, "HttpPut测试成功!", usr_user.USR_USER + "/" + usr_user.USR_NAME + "/" + usr_user.USR_DEPT));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="usr_user"></param>
        /// <returns></returns>
        [HttpDelete]
        public IHttpActionResult HttpDeleteUser([FromBody]MODEL.USR_MSTR usr_user)
        {
            return Ok(ReturnJsonResult.GetJsonResult(1, "HttpDelete测试成功!", usr_user.USR_USER + "/" + usr_user.USR_NAME + "/" + usr_user.USR_DEPT));
        }

    }
View Code UserInfoController

 

2、设计Web Api分层架构