因爲咱們系統時間用的過長,數據量大,設計是採用自增IDjavascript
咱們插入數據的時候把ID也寫進去,咱們能夠採用 關閉和開啓自增標識html
沒有關閉的時候 ,提示一下錯誤,不能修改java
set identity_insert test on 關閉標識 在添加時候 提示成功jquery
set identity_insert 表名 on 關閉git
set identity_insert 表名 off 開啓github
C# 實現自動化打開和關閉可執行文件(或 關閉中止與系統交互的可執行文件)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
string
file =Application.StartupPath+
@"\WinFrm_Main.exe"
;
//運行程序位置
public
Form1()
{
InitializeComponent();
}
private
void
button1_Click(
object
sender, EventArgs e)
{
// StopExe(file);
timer1.Enabled =
false
;
}
private
void
button2_Click(
object
sender, EventArgs e)
{
timer1.Enabled =
true
;
}
void
StopExe(
string
file)
{
Process pr =
new
Process();
//聲明一個進程類對象
pr.StartInfo.FileName = file;
//指定運行的程序,
pr.Start();
//運行
}
void
StartExt()
{
//Process[] p_arry = Process.GetProcesses();//獲得系統全部進程
//for (int i = 0; i < p_arry.Length; i++)//遍歷每一個進程
//{
// if (p_arry[i].ProcessName == "WinFrm_Main" && !p_arry[i].Responding)//發現有名爲QQ的進程
// {
// p_arry[i].Kill();//就結束它。
// return;
// }
//}
Process[] proc = Process.GetProcessesByName(
"WinFrm_Main"
);
//建立一個進程數組,把與此進程相關的資源關聯。
for
(
int
i = 0; i < proc.Length; i++)
{
proc[i].Kill();
//逐個結束進程.
}
System.GC.Collect();
//垃圾回收
}
private
void
timer1_Tick(
object
sender, EventArgs e)
{
Process[] proc = Process.GetProcessesByName(
"WinFrm_Main"
);
//建立一個進程數組,把與此進程相關的資源關聯。
for
(
int
i = 0; i < proc.Length; i++)
{
if
(proc[i].ProcessName ==
"WinFrm_Main"
&& !proc[i].Responding)
//發現有名爲WinFrm_Main的進程 或 WinFrm_Main和電腦中止交互 就退出
{
proc[i].Kill();
//就結束它。
//StopExe(file);
}
}
if
(proc.Length==0)
//啓動
StopExe(file);
System.GC.Collect();
//垃圾回收
}
|
下載地址:http://download.csdn.net/detail/amy1314250/9849891ajax
ajaxfileupload插件上傳圖片功能,用MVC和aspx作後臺各寫了一個案例
HTML代碼 和js 代碼sql
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/js/jquery-1.8.3.min.js"></script> <script src="~/js/ajaxfileupload.js"></script> <script type="text/javascript"> $(function () { $("#butLoad").click(function () { $("#img1").attr("src", "../images/timg.gif"); //調用action $.ajaxFileUpload({ url: "../Upload/UpLoad", secureuri: false, //通常設置爲false fileElementId: 'Img', //文件上傳空間的id屬性 <input type="file" id="Img" name="file" /> dataType: 'json', //返回值類型 success: function (data, status) //服務器成功響應處理函數 { $("#img1").attr("src", data.imgurl); if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); } } }, error: function (data, status, e)//服務器響應失敗處理函數 { alert(e); } }); }); $("#butLoadAsp").click(function () { $("#imgAsp").attr("src", "../images/timg.gif"); //調用aspx $.ajaxFileUpload({ url: "../Ajax/UpLoad.aspx?__Action=UpLoadImg", secureuri: false, //通常設置爲false fileElementId: 'ImgAsp', //文件上傳空間的id屬性 <input type="file" id="Img" name="file" /> dataType: 'json', //返回值類型 success: function (data, status) //服務器成功響應處理函數 { $("#imgAsp").attr("src", data.imgurl); if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); } } }, error: function (data, status, e)//服務器響應失敗處理函數 { alert(e); } }); }); }); function ChImages(obj) { $("#img1").attr("src", obj.value) } </script> </head> <body> <div> <h3>mvc-ajax</h3> <input type="file" id="Img" name="file" onchange="ChImages(this)" /> @*注意:name必定要寫*@ <button id="butLoad">上傳</button> <img src="" id="img1" alt="請選擇圖片" width="200" /> </div> <div> <h3>asp.net-ajax</h3> <input type="file" id="ImgAsp" name="file" /> @*注意:name必定要寫*@ <button id="butLoadAsp">上傳</button> <img src="" id="imgAsp" alt="請選擇圖片" width="200" /> </div> </body> </html>
mvc 控制中代碼json
[HttpPost]//過濾 public JsonResult UpLoad() { HttpFileCollectionBase files = Request.Files;//這裏只能用<input type="file" />纔能有效果,由於服務器控件是HttpInputFile類型 object result = new { error="error", msg="上傳失敗",imgurl= files[0].FileName}; string msg = string.Empty; string error = string.Empty; string imgurl; if (files.Count > 0) { string savePath = Server.MapPath("/") + "UpLoadImg\\";//保存文件地址 //string saveDir = System.Web.HttpContext.Current.Server.MapPath(savePath); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } files[0].SaveAs(savePath + System.IO.Path.GetFileName(files[0].FileName)); msg = " 成功! 文件大小爲:" + files[0].ContentLength; imgurl = "../UpLoadImg/" + files[0].FileName; result =new { error="success", msg= msg, imgurl=imgurl }; } return Json(result, "text/html"); }
aspx.cs 代碼數組
public partial class UpLoad : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string action = Request["__Action"]; if (action==null || action == string.Empty) return; Page p = this; Type pageType = p.GetType(); MethodInfo method = pageType.GetMethod(action); if (method != null) method.Invoke(p, null); } public void UpLoadImg() { HttpFileCollection files = Request.Files;//這裏只能用<input type="file" />纔能有效果,由於服務器控件是HttpInputFile類型 // object result = new { error = "error", msg = "上傳失敗", imgurl = files[0].FileName }; string result = "{ error:'error', msg:'上傳失敗',imgurl:'" + files[0].FileName + "'}"; string msg = string.Empty; string error = string.Empty; string imgurl; if (files.Count > 0) { string savePath = Server.MapPath("/") + "UpLoadImg\\";//保存文件地址 //string saveDir = System.Web.HttpContext.Current.Server.MapPath(savePath); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } files[0].SaveAs(savePath + System.IO.Path.GetFileName(files[0].FileName)); msg = " 成功! 文件大小爲:" + files[0].ContentLength; imgurl = "../UpLoadImg/" + files[0].FileName; result = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}"; } Response.Clear(); Response.Write(result.ToString()); Response.End(); } }
MVC和aspx 有些不一樣,MVC獲取HttpInputFile 用HttpFileCollectionBase 類,aspx獲取HttpInputFile 用HttpFileCollection 類
我的學習,請多多指教
代碼:http://files.cnblogs.com/files/BensonHai/UploadImage.rar 本人是用VS2015寫的
將小寫阿拉伯數字轉換成大寫的漢字,
#region 小寫轉大寫
/// <summary> ///
/// 金額轉爲大寫金額
/// </summary>
/// <param name="LowerMoney"></param> <returns></returns>
public static string MoneyToChinese(decimal NubMoney)
{
string LowerMoney = NubMoney.ToString();
string functionReturnValue = null;
bool IsNegative = false;
// 是不是負數
if (LowerMoney.Trim().Substring(0, 1) == "-")
{ // 是負數則先轉爲正數
LowerMoney = LowerMoney.Trim().Remove(0, 1);
IsNegative = true;
}
string strLower = null;
string strUpart = null; string strUpper = null; int iTemp = 0;
// 保留兩位小數 123.489→123.49 123.4→123.4
LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
if (LowerMoney.IndexOf(".") > 0)
{
if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
{ LowerMoney = LowerMoney + "0"; }
}
else
{
LowerMoney = LowerMoney + ".00";
} strLower = LowerMoney; iTemp = 1; strUpper = ""; while (iTemp <= strLower.Length)
{
switch (strLower.Substring(strLower.Length - iTemp, 1))
{
case ".": strUpart = "圓";
break;
case "0": strUpart = "零"; break;
case "1": strUpart = "壹";
break;
case "2": strUpart = "貳"; break;
case "3": strUpart = "叄";
break;
case "4": strUpart = "肆"; break;
case "5": strUpart = "伍";
break;
case "6": strUpart = "陸"; break;
case "7": strUpart = "柒";
break;
case "8": strUpart = "捌"; break;
case "9": strUpart = "玖";
break;
} switch (iTemp)
{
case 1: strUpart = strUpart + "分";
break;
case 2: strUpart = strUpart + "角"; break;
case 3:
strUpart = strUpart + ""; break;
case 4: strUpart = strUpart + "";
break;
case 5: strUpart = strUpart + "拾"; break;
case 6:
strUpart = strUpart + "佰"; break;
case 7: strUpart = strUpart + "仟";
break;
case 8: strUpart = strUpart + "萬"; break;
case 9:
strUpart = strUpart + "拾"; break;
case 10:
strUpart = strUpart + "佰"; break;
case 11:
strUpart = strUpart + "仟"; break;
case 12:
strUpart = strUpart + "億"; break;
case 13:
strUpart = strUpart + "拾"; break;
case 14:
strUpart = strUpart + "佰"; break;
case 15:
strUpart = strUpart + "仟"; break;
case 16:
strUpart = strUpart + "萬"; break;
default:
strUpart = strUpart + ""; break;
}
strUpper = strUpart + strUpper; iTemp = iTemp + 1;
} strUpper = strUpper.Replace("零拾", "零");
strUpper = strUpper.Replace("零佰", "零"); strUpper = strUpper.Replace("零仟", "零"); strUpper = strUpper.Replace("零零零", "零");
strUpper = strUpper.Replace("零零", "零"); strUpper = strUpper.Replace("零角零分", "整"); strUpper = strUpper.Replace("零分", "整");
strUpper = strUpper.Replace("零角", "零"); strUpper = strUpper.Replace("零億零萬零圓", "億圓");
strUpper = strUpper.Replace("億零萬零圓", "億圓"); strUpper = strUpper.Replace("零億零萬", "億");
strUpper = strUpper.Replace("零萬零圓", "萬圓"); strUpper = strUpper.Replace("零億", "億");
strUpper = strUpper.Replace("零萬", "萬"); strUpper = strUpper.Replace("零圓", "圓");
strUpper = strUpper.Replace("零零", "零");
// 對壹圓如下的金額的處理
if (strUpper.Substring(0, 1) == "圓")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
} if (strUpper.Substring(0, 1) == "零")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
}
if (strUpper.Substring(0, 1) == "角")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
} if (strUpper.Substring(0, 1) == "分")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
} if (strUpper.Substring(0, 1) == "整")
{
strUpper = "零圓整";
} functionReturnValue = strUpper; if (IsNegative == true)
{
return "負" + functionReturnValue;
}
else { return functionReturnValue; }
}
/// <summary> ///
/// 金額轉爲大寫金額
/// </summary>
/// <param name="LowerMoney"></param> <returns></returns>
public static string NumberToChinese(decimal NubMoney)
{
string LowerMoney = NubMoney.ToString();
string functionReturnValue = null;
bool IsNegative = false;
// 是不是負數
if (LowerMoney.Trim().Substring(0, 1) == "-")
{ // 是負數則先轉爲正數
LowerMoney = LowerMoney.Trim().Remove(0, 1);
IsNegative = true;
}
string strLower = null;
string strUpart = null; string strUpper = null; int iTemp = 0;
// 保留兩位小數 123.489→123.49 123.4→123.4
LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
if (LowerMoney.IndexOf(".") > 0)
{
if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
{ LowerMoney = LowerMoney + "0"; }
}
else
{
LowerMoney = LowerMoney + ".00";
} strLower = LowerMoney; iTemp = 1; strUpper = ""; while (iTemp <= strLower.Length)
{
switch (strLower.Substring(strLower.Length - iTemp, 1))
{
case ".": strUpart = "";
break;
case "0": strUpart = "零"; break;
case "1": strUpart = "一";
break;
case "2": strUpart = "二"; break;
case "3": strUpart = "三";
break;
case "4": strUpart = "四"; break;
case "5": strUpart = "五";
break;
case "6": strUpart = "六"; break;
case "7": strUpart = "七";
break;
case "8": strUpart = "八"; break;
case "9": strUpart = "九";
break;
}
switch (iTemp)
{
case 1: strUpart = strUpart + "";
break;
case 2: strUpart = strUpart + ""; break;
case 3:
strUpart = strUpart + ""; break;
case 4: strUpart = strUpart + "";
break;
case 5: strUpart = strUpart + "拾"; break;
case 6:
strUpart = strUpart + "佰"; break;
case 7: strUpart = strUpart + "仟";
break;
case 8: strUpart = strUpart + "萬"; break;
case 9:
strUpart = strUpart + "拾"; break;
case 10:
strUpart = strUpart + "佰"; break;
case 11:
strUpart = strUpart + "仟"; break;
case 12:
strUpart = strUpart + "億"; break;
case 13:
strUpart = strUpart + "拾"; break;
case 14:
strUpart = strUpart + "佰"; break;
case 15:
strUpart = strUpart + "仟"; break;
case 16:
strUpart = strUpart + "萬"; break;
default:
strUpart = strUpart + ""; break;
}
strUpper = strUpart + strUpper; iTemp = iTemp + 1;
}
strUpper = strUpper.Replace("零拾", "零");
strUpper = strUpper.Replace("零佰", "零");
strUpper = strUpper.Replace("零仟", "零");
strUpper = strUpper.Replace("零零零", "零");
strUpper = strUpper.Replace("零零", "零");
strUpper = strUpper.Replace("零角零分", "整");
strUpper = strUpper.Replace("零分", "整");
strUpper = strUpper.Replace("零角", "零");
strUpper = strUpper.Replace("零億零萬零圓", "億圓");
strUpper = strUpper.Replace("億零萬零圓", "億圓");
strUpper = strUpper.Replace("零億零萬", "億");
strUpper = strUpper.Replace("零萬零圓", "萬圓");
strUpper = strUpper.Replace("零億", "億");
strUpper = strUpper.Replace("零萬", "萬");
if (strUpper.IndexOf("一億萬") > -1)
strUpper = strUpper.Replace("萬","");
strUpper = strUpper.Replace("零圓", "圓");
strUpper = strUpper.Replace("零零", "零");
// 對壹圓如下的金額的處理
if (strUpper.Substring(0, 1) == "圓")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
} if (strUpper.Substring(0, 1) == "零")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
}
if (strUpper.Substring(0, 1) == "角")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
} if (strUpper.Substring(0, 1) == "分")
{
strUpper = strUpper.Substring(1, strUpper.Length - 1);
} if (strUpper.Substring(0, 1) == "整")
{
strUpper = "零圓整";
}
if (strUpper.LastIndexOf("零") > -1) {
strUpper = strUpper.Substring(0, strUpper.Length - 1);
}
functionReturnValue = strUpper;
if (IsNegative == true)
{
return "負" + functionReturnValue;
}
else { return functionReturnValue; }
}
#endregion
C# WinForm 中英文實現, 國際化實現的簡單方法
來源:http://www.jb51.net/article/45675.htm,今天看到了借鑑過了,保存一下,下次開發直接用嘻嘻
軟件行業發展到今天,國際化問題一直都佔據很是重要的位置,並且應該愈來愈被重視。對於開發人員而言,在編寫程序以前,國際化問題是首先要考慮的一個問題,也許有時候這個問題已經在設計者的考慮範圍以內,但終歸要開發人員去作實現的。所以,如何實現國際化,是開發人員必須掌握的一項基本技能。
今天,這裏要講的就是,在利用C#進行WinForm開發時,國際化是怎麼實現的。鑑於時間及篇幅關係,這裏僅僅介紹一種簡單的國際化實現方法,可能這裏提到的方法已經有很是多人提到過,但筆者仍是不厭其煩地介紹一下。
要在C#中實現國際化,須要相關資源文件,好比要在一個軟件中支持英文、中文兩種語言,那麼就必須有這兩種語言的資源文件,這在C#中能夠採用資源文件(後綴名爲.resx)來實現,咱們不妨定義英文資源文件名稱爲Resource.en-US,中文資源文件名稱爲Resource.zh-CN,兩種資源文件所涉及的ID都應該是同樣的(這對於其餘更多的資源文件均是同樣的),只不過是展現的名稱不一樣罷了。
有了這兩種資源文件,接下來就要考慮如何作的問題了。爲了適應多處使用的情形,這裏筆者單獨編寫了一個類ResourceCulture,該類包含了一些靜態方法,主要做用是用來設置當前語言及返回當前的語言的相關字符串。該類代碼以下:
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Globalization;
namespace GlobalizationTest
{
class ResourceCulture
{
/// <summary>
/// Set current culture by name
/// </summary>
/// <param name="name">name</param>
public static void SetCurrentCulture(string name)
{
if (string.IsNullOrEmpty(name))
{
name = "en-US";
}
Thread.CurrentThread.CurrentCulture = new CultureInfo(name);
}
/// <summary>
/// Get string by id
/// </summary>
/// <param name="id">id</param>
/// <returns>current language string</returns>
public static string GetString(string id)
{
string strCurLanguage = "";
try
{
ResourceManager rm = new ResourceManager("GlobalizationTest.Resource", Assembly.GetExecutingAssembly());
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
strCurLanguage = rm.GetString(id, ci);
}
catch
{
strCurLanguage = "No id:" + id + ", please add.";
}
return strCurLanguage;
}
}
}
在Form1中的代碼以下:
/**
* This project is just a example to show how to do the globalization in C# winform.
* You and rebuild and/or modify it by yourself if you want.
* Specially, this project was created in Visual Studio 2010.
*
* Project Name : GlobalizationTest
* Create Date : April 29th, 2010
* */
using System;
using System.Windows.Forms;
namespace GlobalizationTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Set the resource culture
/// </summary>
private void SetResourceCulture()
{
// Set the form title text
this.Text = ResourceCulture.GetString("Form1_frmText");
// Set the groupbox text
this.gbLanguageView.Text = ResourceCulture.GetString("Form1_gbLanguageViewText");
this.gbLanguageSelection.Text = ResourceCulture.GetString("Form1_gbLanguageSelectionText");
// Set the label text
this.lblCurLanguageText.Text = ResourceCulture.GetString("Form1_lblCurLanguageText");
this.lblNameText.Text = ResourceCulture.GetString("Form1_lblNameText");
this.lblPhoneText.Text = ResourceCulture.GetString("Form1_lblPhoneText");
// Set the button text
this.btnMsgShow.Text = ResourceCulture.GetString("Form1_btnMsgShowText");
// Set radiobutton text
this.rbEnglish.Text = ResourceCulture.GetString("Language_EnglishText");
this.rbChinese.Text = ResourceCulture.GetString("Language_ChineseText");
// Set the current language text
if (rbEnglish.Checked)
{
this.lblCurLanguage.Text = ResourceCulture.GetString("Language_EnglishText");
}
else if (rbChinese.Checked)
{
this.lblCurLanguage.Text = ResourceCulture.GetString("Language_ChineseText");
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Set the default language
ResourceCulture.SetCurrentCulture("en-US");
this.SetResourceCulture();
}
private void btnMsgShow_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtName.Text))
{
MessageBox.Show(ResourceCulture.GetString("Form1_msgbox_nameText"), ResourceCulture.GetString("Form1_msgbox_TitleText"),
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (string.IsNullOrEmpty(txtPhone.Text))
{
MessageBox.Show(ResourceCulture.GetString("Form1_msgbox_phoneText"), ResourceCulture.GetString("Form1_msgbox_TitleText"),
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
MessageBox.Show(ResourceCulture.GetString("Form1_msgbox_InfoText") + txtName.Text + ", " + txtPhone.Text,
ResourceCulture.GetString("Form1_msgbox_TitleText"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void rbEnglish_CheckedChanged(object sender, EventArgs e)
{
ResourceCulture.SetCurrentCulture("en-US");
this.SetResourceCulture();
}
private void rbChinese_CheckedChanged(object sender, EventArgs e)
{
ResourceCulture.SetCurrentCulture("zh-CN");
this.SetResourceCulture();
}
}
}
最終的效果以下圖1和圖2所示:
圖1
歸結起來,要在C#的WinForm中實現國際化,至少須要作好如下幾點:
(1)準備所需資源文件(如本文中提到的英文和中文資源文件);
(2)引入命名空間(包括:System.Reflection、System.Resources、System.Threading和System.Globalization);
(3)實例化資源管理器(即ResourceManager);
(4)設置當前進程的語言區域;
(5)經過資源管理器從指定的資源文件中獲取所需值。
經過上述的方法便可簡單實現國際化。
ASP.NET Core 2 學習筆記(三)
以前ASP.NET中使用的HTTP Modules及HTTP Handlers,在ASP.NET Core中已不復存在,取而代之的是Middleware。Middleware除了簡化了HTTP Modules/Handlers的使用方式,還帶入了Pipeline的概念。
本篇將介紹ASP.NET Core的Middleware概念及用法。
Middleware 概念
ASP.NET Core在Middleware的官方說明中,使用了Pipeline這個名詞,意指Middleware像水管同樣能夠串聯在一塊兒,全部的Request及Response都會層層通過這些水管。
用圖例能夠很容易理解,以下圖:
App.Use
Middleware的註冊方式是在Startup.cs的Configure
對IApplicationBuilder
使用Use
方法註冊。
大部分擴展的Middleware也都是以Use開頭的方法註冊,例如:
- UseMvc():MVC的Middleware
- UseRewriter():URL rewriting的Middleware
一個簡單的Middleware 範例。以下:
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Threading.Tasks;
using
Microsoft.AspNetCore.Builder;
using
Microsoft.AspNetCore.Hosting;
using
Microsoft.AspNetCore.Http;
using
Microsoft.Extensions.DependencyInjection;
namespace
MyWebsite
{
public
class
Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public
void
ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public
void
Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if
(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"First Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"First Middleware out. \r\n"
);
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"Second Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"Second Middleware out. \r\n"
);
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"Third Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"Third Middleware out. \r\n"
);
});
app.Run(async (context) =>
{
await context.Response.WriteAsync(
"Hello World! \r\n"
);
});
}
}
}
|
用瀏覽器打開網站任意連結,輸出結果:
1
2
3
4
5
6
7
|
First Middleware
in
.
Second Middleware
in
.
Third Middleware
in
.
Hello World!
Third Middleware out.
Second Middleware out.
First Middleware out.
|
在Pipeline的概念中,註冊順序是很重要的事情。請求通過的順序必定是先進後出。
Request 流程以下圖:
Middleware 也能夠做爲攔截使用,以下:
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Threading.Tasks;
using
Microsoft.AspNetCore.Builder;
using
Microsoft.AspNetCore.Hosting;
using
Microsoft.AspNetCore.Http;
using
Microsoft.Extensions.DependencyInjection;
namespace
MyWebsite
{
public
class
Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public
void
ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public
void
Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if
(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"First Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"First Middleware out. \r\n"
);
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"Second Middleware in. \r\n"
);
// 水管阻塞,封包不日後送
var
condition =
false
;
if
(condition)
{
await next.Invoke();
}
await context.Response.WriteAsync(
"Second Middleware out. \r\n"
);
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"Third Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"Third Middleware out. \r\n"
);
});
app.Run(async (context) =>
{
await context.Response.WriteAsync(
"Hello World! \r\n"
);
});
}
}
}
|
輸出結果:
1
2
3
4
|
First Middleware
in
.
Second Middleware
in
.
Second Middleware out.
First Middleware out.
|
在Second Middleware 中,由於沒有達成條件,因此封包也就不在日後面的水管傳送。流程如圖:
App.Run
Run
是Middleware的最後一個行爲,以上面圖例來講,就是最末端的Action。
它不像Use
能串聯其餘Middleware,但Run
仍是能完整的使用Request及Response。
App.Map
Map
是能用來處理一些簡單路由的Middleware,可依照不一樣的URL指向不一樣的Run
及註冊不一樣的Use
。
新增一個路由以下:
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Threading.Tasks;
using
Microsoft.AspNetCore.Builder;
using
Microsoft.AspNetCore.Hosting;
using
Microsoft.AspNetCore.Http;
using
Microsoft.Extensions.DependencyInjection;
namespace
MyWebsite
{
public
class
Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public
void
ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public
void
Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if
(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"First Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"First Middleware out. \r\n"
);
});
// app.Use(async (context, next) =>
// {
// await context.Response.WriteAsync("Second Middleware in. \r\n");
// // 水管阻塞,封包不日後送
// var condition = false;
// if (condition)
// {
// await next.Invoke();
// }
// await context.Response.WriteAsync("Second Middleware out. \r\n");
// });
app.Map(
"/second"
, mapApp =>
{
mapApp.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"Second Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"Second Middleware out. \r\n"
);
});
mapApp.Run(async context =>
{
await context.Response.WriteAsync(
"Second. \r\n"
);
});
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(
"Third Middleware in. \r\n"
);
await next.Invoke();
await context.Response.WriteAsync(
"Third Middleware out. \r\n"
);
});
app.Run(async (context) =>
{
await context.Response.WriteAsync(
"Hello World! \r\n"
);
});
}
}
}
|
開啓網站任意連結,會顯示:
1
2
3
4
5
|
First Middleware
in
.
Third Middleware
in
.
Hello World!
Third Middleware out.
First Middleware out.
|
開啓網站http://localhost:5000/second
,則會顯示:
1
2
3
4
5
|
First Middleware
in
.
Second Middleware
in
.
Second.
Second Middleware out.
First Middleware out.
|
建立Middleware 類
若是Middleware所有都寫在Startup.cs,代碼將很難維護,因此應該把自定義的Middleware邏輯獨立出來。
創建Middleware類不須要額外繼承其它類或接口,通常的類便可,例子以下:
FirstMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
using
System.Threading.Tasks;
using
Microsoft.AspNetCore.Http;
namespace
MyWebsite
{
public
class
FirstMiddleware
{
private
readonly
RequestDelegate _next;
public
FirstMiddleware(RequestDelegate next)
{
_next = next;
}
public
async Task Invoke(HttpContext context)
{
await context.Response.WriteAsync($
"{nameof(FirstMiddleware)} in. \r\n"
);
await _next(context);
await context.Response.WriteAsync($
"{nameof(FirstMiddleware)} out. \r\n"
);
}
}
}
|
全局註冊
在Startup.Configure
註冊Middleware就能夠套用到全部的Request。以下:
Startup.cs
1
2
3
4
5
6
7
8
9
10
|
// ...
public
class
Startup
{
// ...
public
void
Configure(IApplicationBuilder app)
{
app.UseMiddleware<FirstMiddleware>();
// ...
}
}
|
局部註冊
Middleware 也能夠只套用在特定的Controller 或Action。註冊方式以下:
Controllers\HomeController.cs
1
2
3
4
5
6
7
8
9
10
11
12
|
// ..
[MiddlewareFilter(
typeof
(FirstMiddleware))]
public
class
HomeController : Controller
{
// ...
[MiddlewareFilter(
typeof
(SecondMiddleware))]
public
IActionResult Index()
{
// ...
}
}
|
Extensions
大部分擴展的Middleware都會用一個靜態方法包裝,如:UseMvc()
、UseRewriter()
等。
自定義的Middleware固然也能夠透過靜態方法包,範例以下:
Extensions\CustomMiddlewareExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
|
using
Microsoft.AspNetCore.Builder;
namespace
MyWebsite
{
public
static
class
CustomMiddlewareExtensions
{
public
static
IApplicationBuilder UseFirstMiddleware(
this
IApplicationBuilder builder)
{
return
builder.UseMiddleware<FirstMiddleware>();
}
}
}
|
註冊Extension Middleware 的方式以下:
Startup.cs
1
2
3
4
5
6
7
8
9
10
|
// ...
public
class
Startup
{
// ...
public
void
Configure(IApplicationBuilder app)
{
app.UseFirstMiddleware();
// ...
}
}
|
參考
ASP.NET Core Middleware Fundamentals
Creating Custom Middleware In ASP.Net Core
老司機發車啦:https://github.com/SnailDev/SnailDev.NETCore2Learning
ASP.NET Core 2 學習筆記(六)
ASP.NET Core MVC跟ASP.NET MVC觀念是一致的,使用上也沒有什麼太大的變化。以前的ASP.NET MVC把MVC及Web API的套件分開,但在ASP.NET Core中MVC及Web API用的套件是相同的。
本篇將介紹ASP.NET Core MVC設置方式。
MVC 簡介
ASP.NET Core的MVC(Model-View-Controller)架構模式延續ASP.NET MVC,把網站分紅三大元件Model、View及Controller,依賴關係以下圖:
- Model
負責數據處理,包含數據存取、業務邏輯、定義數據對象及驗證數據。 - View
負責UI顯示,如HTML、CSS等界面設計配置。 - Controller
負責將使用者Requset找到相對應的Model及View,作爲控制流程的角色。
在ASP.NET Core中使用MVC或Web API,須要
Microsoft.AspNetCore.Mvc
套件。
註冊MVC 服務
在Startup.cs的ConfigureServices
加入MVC的服務,並在Configure
對IApplicationBuilder
使用UseMvcWithDefaultRoute
方法註冊MVC預設路由的Middleware。以下:
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// ...
public
class
Startup
{
public
void
ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public
void
Configure(IApplicationBuilder app)
{
app.UseMvcWithDefaultRoute();
}
}
|
- UseMvcWithDefaultRoute
這個是ASP.NET Core的預設路由,會將Request來的URL找到對應的Controller及Action。
MVC 示例
Model
創建一個簡單的Model 用於Controller 跟View 互動。
Models\UserModel.cs
1
2
3
4
5
6
7
8
|
namespace
MyWebsite.Models
{
public
class
UserModel
{
// 名稱
public
string
Name {
get
;
set
; } =
"SnailDev"
;
}
}
|
Controller
在項目目錄下創建一個Controllers文件夾,把Controller都放這個目錄。
過去ASP.NET把MVC及Web API用的Controller分爲Controller
及ApiController
,如今ASP.NET Core把二者合一,再也不區分ApiController
。
因此要創建一個類,名稱後綴Controller便可,以下:
Controllers\HomeController.cs
1
2
3
4
5
6
7
8
9
10
|
namespace
MyWebsite.Controllers
{
public
class
HomeController
{
public
string
Index()
{
return
"this is homecontroller index action"
;
}
}
}
|
但要讓Controller跟View互動,仍是須要繼承Controller
比較方便,以下:
Controllers\HomeController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using
Microsoft.AspNetCore.Mvc;
using
MyWebsite.Models;
namespace
MyWebsite.Controllers
{
public
class
HomeController : Controller
{
public
IActionResult Index()
{
var
user =
new
UserModel();
return
View(model: user);
}
}
}
|
IActionResult
回傳的方式能夠有不少種,經過繼承Controller
後,就可使用Controller
的方法:
- View
以上例來講,經過回傳View
方法,能夠找到該Controller & Action對應的*.cshtml
,而且把UserModel傳給View使用。 - HTTP Status Code
響應包含HTTP Status。經常使用的響應有Ok
、BadRequest
、NotFound
等。
例如:return BadRequest("Internal Server Error")
,會響應HTTP Status 400及Internal Server Error字串。 - Redirect
能夠把Request轉給其餘的Action或URL。轉向的方法有Redirect
、LocalRedirect
、RedirectToAction
、RedirectToRoute
等。
例如:return RedirectToAction("Login", "Authentication")
,就會把Request轉向到AuthenticationController的Login()。 - Formatted Response
響應時指定Content-Type。Web API的回傳一般都用這種方式,序列化對象順便標註Content-Type。
例如:return Json(user)
,會將對象序列化成JSON字串,並在HTTP Headers帶上Content-Type=application/json。
View
View跟Controller有相互的對應關係,預設在Controller使用View
方法回傳結果,會從如下目錄尋找對應的*.cshtml
:
- Views\{ControllerName}\{ActionName}.cshtml
尋找與Controller同名的子目錄,再找到與Action同名的*.cshtml
。
如上例HomeController.Index()
,就會找項目目錄下的Views\Home\Index.cshtml
文件。 - Views\Shared\{ActionName}.cshtml
若是Controller同名的子目錄,找不到Action同名的*.cshtml
。就會到Shared目錄找。如上例HomeController.Index()
,就會找項目目錄下的Views\Shared\Index.cshtml文件
。
Views\Home\Index.cshtml
1
2
3
|
@model MyWebsite.Models.UserModel
Hello~ 我是 @Model.Name
|
在*.cshtml
用@model
綁定Model的型別,纔可使用@Model
取得Controller傳入的對象。
示例結果
數據流動圖以下:
參考
Overview of ASP.NET Core MVC
ASP.NET Core - Setup MVC
老司機發車啦:https://github.com/SnailDev/SnailDev.NETCore2Learning