【C#MVC4】菜單管理和訪問權限分配(一)

今天開始,寫一個關於菜單管理的小例子,加深對mvc的使用。爲什麼選擇菜單管理呢,因爲中大型後臺系統,根據用戶角色的不同,均會做用戶權限的分配。所以這個用處還是很廣的,尤其對初學者而言,大部分公司都會將這部分不是很重要的放給新人做,讓他們熟悉一下開發環境和開發流程。

這個項目暫時是由我空閒時間更新,所以可能會很慢,若有需要這個項目的代碼,或者你做到更新的地方,想繼續學下去,或者有問題的朋友,可以私聊我,我會進行相關的解答,和開放源代碼。由於剛開始寫博客,語言組織可能不是很好,有什麼意見或是建議歡迎評論。

項目的工具是:VS2013,SqlServer2014,
表的結構是:

這裏寫圖片描述

總共三張表,用途分別爲:
User_Master:用戶的登錄表,這裏沒什麼作用,也沒有寫過多的驗證,只是用來登錄系統。
Menu_List:菜單表,用於存放菜單按鈕。Id,唯一標識列;Request_URL,請求路徑;Name,菜單名;Serial,菜單位置標識;Menu_Level:菜單所屬的等級/父菜單的ID;Icon_Name,菜單的圖片。
Menu_List_Access:用戶權限分配表。Id,唯一標示列;User_Master_Id,用戶的Id;Menu_List_I,所屬菜單的Id;

服務器端框架:EF6.0、並沒有使用什麼集成框架。
前段框架:EasyUI
開發模式:asp.net MVC4
項目結構:Common層:工具類
Model層:實體層,使用EF生成表的實體模型
Service層:持久層,使用Linq進行數據交換
Manager層:這裏沒有太大意義,但是保留習慣。
Controller層:控制層,進行數據的處理和視圖的轉發
View層,視圖層,包含各個頁面

大致業務流程:並沒什麼業務其實….就是將menu按角色分配給不同的用戶,比如一般系統分爲,客服,站點管理員,全局管理員,操作員等,這些人員的登錄進入系統後,顯示的菜單是不同的。進入系統後,系統就會去根據User_Master_Id去加載User_Menu_Access表,找到對應的Menu後,加載顯示在一個tree上面。這樣就做到了權限的分配。然後這裏我們演示了一個菜單的管理,就是你新建一個頁面之後,需要使用菜單管理將這個頁面掛載到menu_list表中,管理員才能對其進行分配。

上面講的可能有點亂,但是我相信既然你點進這個鏈接說明你是對這個流程較爲了解的了,因爲語言組織有點差,我寫博客的目的之一也是爲了鍛鍊自己的語言表達,能到達到清晰的表達自己的想法的程度就行了。

項目的初始搭建工作我就不再重複了,在我之前寫的一個項目裏有,這個也是接着那個項目做的 http://blog.csdn.net/f627422467/article/details/52319131

這裏引入EasyUI的文件:直接放到項目目錄下即可,但是重新打開項目,將剛剛的文件夾 包含在項目中。(會不會有初學者不知道如何將文件包含在項目中? 真有不會的可以私聊或是評論區留言哦)

最後項目的目錄結構應該是這樣的:

這裏寫圖片描述

接下來是做一個登錄的功能,但是篇幅有限,這一篇就做一些準備工作好了。

Common類下面添加一些公用的工具類,雖然這樣違反了 最少知道原則增加了程序一定的耦合度,但是該做取捨時,要適度。

Utility:(裏面提供了很多常用的工具類)

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Arise.Common
{
    public class Utility
    {

        public static int ConvertToInt32(string num)
        {
            try
            {
                return Convert.ToInt32(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
        public static int ConvertToInt32(Object obj)
        {
            try
            {
                return Convert.ToInt32(obj.ToString());
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static short ConvertToShort(string num)
        {
            try
            {
                return short.Parse(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static decimal ConvertToDecimal(string num)
        {
            try
            {
                return Convert.ToDecimal(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }
        public static decimal ConvertToDecimal(decimal? num)
        {
            try
            {
                return Convert.ToDecimal(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }
        public static decimal ConvertToDecimal(Object obj)
        {
            try
            {
                return Convert.ToDecimal(obj.ToString());
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static double ConvertToDouble(decimal num)
        {
            try
            {
                return Convert.ToDouble(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }
        public static double ConvertToDouble(Object obj)
        {
            try
            {
                return Convert.ToDouble(obj);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static DateTime ConvertToDatetime(string value)
        {
            try
            {
                return Convert.ToDateTime(value);
            }
            catch (Exception)
            {
                return DateTime.Now;
            }
        }

        public static DateTime ConvertToDatetime(object value)
        {
            try
            {
                return Convert.ToDateTime(value.ToString());
            }
            catch (Exception)
            {
                return DateTime.Now;
            }
        }

        public static DateTime GetCurrentDateTime(double GMT)
        {
            try
            {
                return DateTime.Now.ToUniversalTime().AddHours(GMT);
            }
            catch (Exception)
            {
                return DateTime.Now.ToUniversalTime();
            }
        }

        public static Exception GetInnerException(Exception exception)
        {
            if (exception.InnerException != null)
            {
                return GetInnerException(exception.InnerException);
            }
            return exception;
        }

        public static string GetFinnalExceptionMessage(Exception exception)
        {
            if (exception.InnerException != null)
            {
                return GetFinnalExceptionMessage(exception.InnerException);
            }
            return exception.Message;
        }

        /// <summary>
        /// Convert Date dd/MM/yyyy to MM/dd/yyyy or MM/dd/yyyy to dd/MM/yyyy
        /// </summary>
        /// <param name="strDate"></param>
        /// <returns></returns>
        public static string ConvertDate(string strDate)
        {
            string date = "";
            string[] TempDate;
            if (strDate != "")
            {
                TempDate = strDate.Split('/');
                date = TempDate[1].ToString() + "/" + TempDate[0].ToString() + "/" + TempDate[2].ToString();
            }
            return date;
        }

        public static JsonResult ReturnJsonResult(string result, string message)
        {
            return new JsonResult
            {
                Data = new { result = result, message = message },
            };
        }

        public static JsonResult ReturnJsonResult(string result)
        {
            JsonResult js = new JsonResult();
            js.Data = result;
            return js;
        }

        public static JsonResult ReturnJsonResult<T>(T t)
        {
            JsonResult js = new JsonResult();
            js.Data = t;
            return js;
        }

        /// <summary>
        /// 轉換爲Json格式
        /// </summary>
        /// <param name="obj">要轉換的對象</param>
        /// <returns>結果Json對象</returns>
        public static string ToJson(object obj)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "dd/MM/yyyy";
            return JsonConvert.SerializeObject(obj, timeConverter);
        }

        public static string ToJsonIgnoreForeignKey(object obj)
        {
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
            jsonSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            return JsonConvert.SerializeObject(obj, jsonSerializerSettings);
        }

        /// <summary>
        /// 轉換爲帶記錄總數的Json格式
        /// </summary>
        /// <param name="obj">要轉換的對象</param>
        /// <param name="total">記錄總數</param>
        /// <returns>結果Json對象</returns>
        public static string ToGridJson(object obj, int total)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "dd/MM/yyyy";
            Hashtable hash = new Hashtable();
            hash["total"] = total;
            hash["rows"] = obj;
            return (JsonConvert.SerializeObject(hash, timeConverter)).Replace("\r\n", " ").Replace("\n", "");
        }
        public static string ToGridJsonWithTime(object obj, int total)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "dd/MM/yyyy HH:mm:ss";
            Hashtable hash = new Hashtable();
            hash["total"] = total;
            hash["rows"] = obj;
            return (JsonConvert.SerializeObject(hash, timeConverter)).Replace("\r\n", " ").Replace("\n", "");
        }



        /// <summary>
        /// 使Json反序列化
        /// </summary>
        /// <typeparam name="T">反序列化類型</typeparam>
        /// <param name="obj">Json</param>
        /// <returns>結果對象</returns>
        public static T Deserialize<T>(string obj)
        {
            return JsonConvert.DeserializeObject<T>(obj);
        }

        public static DataTable JsonToDataTable(string strJson)
        {
            //取出表名   
            Regex rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //獲取數據   
            Regex rgData = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rgData.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');

                //創建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        DataColumn dc = new DataColumn();
                        string[] strCell = str.Split(':');
                        dc.ColumnName = strCell[0].Replace("\"", "");
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加內容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split(':')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "").Replace("null", "").Replace("NULL", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;

        }

        public static string DataTableToJson(DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]");
            return Json.ToString();
        }

        public static void DeleteFile(string fileNameAndPath)
        {
            if (System.IO.File.Exists(fileNameAndPath))
            {
                System.IO.File.Delete(fileNameAndPath);
            }
        }

    }
}

LogHelper:日誌工具類,這裏可已經錯誤日誌記錄下來,保存在物理路徑中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.IO;

namespace Arise.Common
{
    public static class LogHelper
    {
        public static string RecordError(Exception exception)
        {
            string Url = HttpContext.Current.Request.RawUrl;//錯誤發生地址            
            string errorMessage = Utility.GetFinnalExceptionMessage(exception);
            try
            {
                string path = ConfigurationManager.AppSettings["TempFilePath"].ToString().Trim();
                string year = DateTime.Now.ToString("dd/MM/yyyy").Substring(6, 4);
                string month = DateTime.Now.ToString("dd/MM/yyyy").Substring(3, 2);
                string day = DateTime.Now.ToString("dd/MM/yyyy").Substring(0, 2);
                path += @"ErrorLog\" + year + month;
                if (!Directory.Exists(path)) //如果文件夾不存在,則創建文件夾(每個月一個文件夾)
                {
                    Directory.CreateDirectory(path);
                }

                string fileName = @"\ErrorLog" + year + month + day + ".txt";
                path += fileName;

                if (!File.Exists(path)) //如果文件不存在,則創建文件(每天一個文件)
                {
                    File.Create(path).Close();
                }

                StreamWriter writer = new StreamWriter(path, true);
                String date = DateTime.Now.ToString();
                writer.WriteLine("\r\n" + date);
                writer.WriteLine("Message: ");
                writer.WriteLine("\t" + errorMessage);                
                writer.Close();
                return errorMessage;
            }
            catch (Exception)
            {                
                throw new Exception(errorMessage);
            }            
        }
        public static string GetFinnalExceptionMessage(Exception exception)
        {
            if (exception.InnerException != null)
            {
                return GetFinnalExceptionMessage(exception.InnerException);
            }
            return exception.Message;
        }
    }
}

UserMessageShow:(常用的信息,有效的避免了在代碼中硬編碼)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arise.Common
{
    public static class UserMessageShow
    {
        public static string ErrorPassword = "Your Password OR UserName is Error!";
        public static string ErrorLogin = "Your have alreadly Login System!";
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章