ASP-NET-C-Tutorial

ASP.NET C# 判斷HTTP來源類型,取得HTTP 請求(GET, POST)參數

ASP.NET C# 判斷HTTP來源類型,取得HTTP 請求(GET, POST)參數

透過 C# for ASP.NET 的 Response 可以取得HTTP請求相關訊息

取得HTTP Request 類型

可以透過下面兩種方式取得HTTP Request 類型 (GET、POST…)

Request.RequestType
HttpContext.Current.Request.HttpMethod

取得 GET 參數

透過 Request.QueryString[“Key”] 可以取得 GET 參數

取得 POST 參數

透過 Request.Form[“Key”] 可以取得 POST 參數

取得HTTP 參數

如果不區分 GET POST ,透過 Request[“Key”] 只要key相符就取得

若GET POST 同時有相同的key,就會以GET為主

判斷是否為頁面 POST_BACK

當表單在同頁送出POST,就可以用 Page.IsPostBack 來偵測

範例

下方示範 HTTP 請求:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 取得HTTP Request 類型
        Response.Write(HttpContext.Current.Request.HttpMethod + "<BR>");//GET, POST...
        // 取得HTTP Request 類型
        Response.Write(Request.RequestType + "<BR>");//GET, POST...

        if (Request.RequestType == "GET")
        {
            //取得 GET 值
            Response.Write(Request.QueryString["TextBox1"] + "<BR>");
        }
        if (Request.RequestType == "POST")
        {
            //取得 POST 值 - 欄位名稱 TextBox1
            Response.Write(Request.Form["TextBox1"] + "<BR>");
        }

        // 不管GET或POST,都會取得值 (以 GET 值為優先)
        Response.Write("Always show:" + Request["TextBox1"] + "<BR>");

        if (Page.IsPostBack)
        {
            Response.Write("PAGE POST BACK<br>");
        }

    }
}

Continue Reading

ASP.NET C# JSON 格式轉換

ASP.NET JSON 格式轉換

在這裡,選擇透過 (Json.NET)[https://www.newtonsoft.com/json/help/html/Introduction.htm] 這款套件來協助處理物件轉換為JSON格式

Continue Reading

ASP.NET C# - 如何取得來源 IP

取得 Clinet 來源IP的方式如下:

Continue Reading

ASP.NET C# 生命週期

ASP.NET 生命週期

ASP.NET 可以動態的生成頁面,而運作的架構生命週期主要可以分為:

  • 應用程式生命週期(Application Life Cycle)
  • 頁面生命週期(Page Life Cycle)

[應用程式生命週期(Application Life Cycle)]

  1. 當使用者透過瀏覽器訪問時,瀏覽器會先向web server傳送請求,
  2. 在 server 端在一開始都會先執行:
  • 建立 ApplicationManager Class 物件
  • 建立 HostingEnvironment Class 物件,提供請求來源有關的訊息。
  • 建立應用程式初始成員
  1. 建立 Response 物件,包括 HttpContext,HttpRequest,HttpResponse 都會在這時被初始化建立
  2. HttpApplication 物件被實體化,並且被指派給 request
  3. Request 被 HttpApplication class 處理,並根據處理的結果呼叫不同事件

[頁面生命週期(Page Life Cycle)]

當頁面被請求,會先被載入 server 的記憶體中進行處理,接著再傳送回瀏覽器,再將項目從記憶體中卸載

整個頁面生命週期主要有

初始化 (Initialization) 實體化頁面控制 (Instantiation of the controls on the page) 階段修復及維護 執行事件處理程式 顯示頁面

下方列出 ASP.NET 頁面不同階段

  • 網頁要求(Page Request)

  • 開始進入生命週期(Starting of page life cycle) 在這階段,會檢查來源物件,如果是舊的請求或者是表單 post back,就會將 IsPostBack屬性設定為true

    Continue Reading

ASP.NET 基礎入門 Hello World

ASP.NET 基礎入門 Hello World

在開始前要先建立專案及項目

新增專案

檔案>新增>專案

ASP.NET 空網站

加入新項目

在專案目錄最外層,右鍵>加入>加入新項目 Web表單

簡單練習輸出文字

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<% 
    string mytxt = "Hello World"; 
    HelloWorldLabel.Text = "Hello World2";
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <div>
        輸出文字:
        <% Response.Write(mytxt); %> 
        ,也可以這樣寫:
        <%=mytxt %>
    </div>
    <div>
         <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
    </div>
</body>
</html>

每一個 aspx 檔案都會有對應的 code behind

點選目錄中的 Default.aspx.cs 或者按F7 就能切換

預設這裡面都僅會有基本框架

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
}

https://www.tutorialspoint.com/asp.net/index.htm

Continue Reading

ASP.NET 啟用跨站API請求 “Access-Control-Allow-Origin”

ASP.NET 啟用跨站API請求 “Access-Control-Allow-Origin” 簡易設定方式有兩種

1.設定 web.config

Continue Reading

C# LINQ 查詢運算式 - 教學筆記 (使用visual studio)

LINQ 查詢運算式(Language-Integrated Query)是一種數據查詢語言,可以讓我們使用同一個語句來對不同資料來做資料查詢 (包括Objects、SQL、Datasets、Entities、Data Source、XML/XSD等),並且具有擴充性。

使用的方式很簡單 首先,要先載入System.Linq 命名空間類別庫就可以開始使用 LINQ 類別和介面

Continue Reading

C# 系統集合泛型(System.Collections.Generic) Queue, Stack - 教學筆記 (使用visual studio)

C# 在系統集合泛型(System.Collections.Generic) 還包含 佇列(Queue)及堆疊(Stack)

這裡先簡單總結一下兩者的差異

佇列(Queue) 屬於先進先出(FIFO)的集合,例如: 一群人在排隊等公車,先來的就可以先上車。

堆疊(Stack) 屬於後進先出 (LIFO)的集合,例如: 將大箱子放入貨車櫃,最後放進去的,到時會最先取出來; 將子彈裝進彈匣,最後裝進去的會先擊發。

接下來,兩者說明如下:

Continue Reading

C# 系統集合泛型(System.Collections.Generic) List, Dictionary - 教學筆記 (使用visual studio)

前面,我們介紹過C#的泛型 可以讓我們自行設計泛型方法、類別來進行操作資料

在這裡,會說明C#預設提供的泛型集合類別(generic collection classes) 讓我們可以直接拿來使用於操作資料 這些類別主要都被包含在一個Class裡面,稱為系統集合泛型(System.Collections.Generic) 在這裡會介紹 List, Dictionary, Queue, Stack 集合類別

Continue Reading

C# 泛型(Generics) - 教學筆記 (使用visual studio)

C# 提供了泛型,讓我們可以用更有彈性的方式來設計Class、Method,操作資料

透過泛型類型 <型別參數T>來代表型別(int, string, double…)

可以在宣告時再指定型別,

以下透過範例來說明幾種情況的用法:

方法泛型 (Generic Method)

在Method使用泛型,只要在Method後面接上泛型類型 <型別參數T> 就可以在宣告時,再指定型別, 並且,可以搭配.GetType()來檢查型別 範例:

static void MyDemo<T>(T x)
{
    Console.WriteLine("您傳入的型別為"+x.GetType()+ ",值=" + x);
}

static void Main(string[] args)
{
    MyDemo<string>("Hello");//您傳入的型別為System.String,值=Hello
    MyDemo<int>(3);//您傳入的型別為System.Int32,值=3
    MyDemo<double>(3.14);//您傳入的型別為System.Double,值=3.14
}

類別泛型(Generics Class)

在class使用泛型,一樣直接加上 <型別參數T> 即可 在這裡示範如何透過Class泛型來手動做一個簡易的list功能

範例:

// Declare the generic class.
public class MyListClass<T>
{
	//初始化array,並參考泛型別
    T[] innerArray = new T[0];
    
	//Add Method - 新增一個array項目
    public void Add(T item)
    {
        Array.Resize(ref innerArray, innerArray.Length + 1);
        innerArray[innerArray.Length - 1] = item;
    }
    
	//Get Method - 取得array特定key的value
    public T Get(int k) {
        return innerArray[k];
    }
	//All Method - return array
    public T[] All()
    {
        return innerArray;
    }
}

static void Main(string[] args)
{
    // Declare a list of type int.
    MyListClass<int> listA = new MyListClass<int>();
    listA.Add(3);
    listA.Add(4);
    listA.Add(5);
    listA.Add(2);
    foreach (int row in listA.All()) {
        Console.WriteLine(row);
    }
}

Continue Reading

C# 用 system.IO 操作檔案 - 教學筆記 (使用visual studio)

使用C# System.IO namespace,可以用在檔案建立、寫入、讀取…

在這裡,主要介紹 System.IO 的 File Class

WriteAllText 寫入/建立檔案

透過WriteAllText可以將文字寫入檔案(如果檔案不存在,會自動建立),格式為:

File.WriteAllText(檔案位置及名稱, 字串);

範例:

string x = "Hello text";
File.WriteAllText("myfilename.txt", x);

ReadAllText 讀取文件

使用ReadAllText可以直接讀取文件中的內容,格式為:

File.ReadAllText(檔案位置及名稱);

建立檔案 & 讀取檔案 範例:

//建立檔案
string x = "Hello text";
File.WriteAllText("myfilename.txt", x);
//讀取檔案
string y = File.ReadAllText("myfilename.txt");
Console.WriteLine(y); 

AppendAllText 插入文字

C# 將字串插入文件內容尾端 範例:

File.AppendAllText("myfilename.txt", " append text to the end.");
string y = File.ReadAllText("myfilename.txt");
Console.WriteLine(y);

Exists 判斷檔案是否存在

透過 Exists 可以判斷檔案是否已經存在 返回布林值

File.Exists(檔案位置及名稱);

範例

if (File.Exists("myfilename.txt")) {
    Console.WriteLine("Yes");
}else{
    Console.WriteLine("No");
}

Delete 刪除檔案

刪除指定的檔案

Continue Reading

C# try-catch 例外處理(Execption Handling) - 教學筆記 (使用visual studio)

例外處理,可以處理一些未知且發生錯誤的情況,例如: 輸入不合法(型別不符)的值、找不到要開啟的資料、處理資料時突然失去連線…。

在C# 例外處理使用 try-catch 陳述式

只要將一般陳述式放在try區塊,

當try區塊發生發生時,就會移向catch區塊,用Exception擷取錯誤

Continue Reading

C# 結構(Structs) - 教學筆記 (使用visual studio)

C# 的 Struct 是一個value type的小群組,

在管理程式變數時,非常好用

例如,對於註冊用戶資料,會包含姓名、性別、住址…. 透過struct,就可以將用戶資料統整成一個群組結構

Continue Reading

C# 運算子實現類別多載 - 教學筆記 (使用visual studio)

Operator Overloading on Class

在C#設計Class,可以搭配運算子(operator)來做到多載(overloading) 並且,要Overloading的運算子,必須是 static 例如:

        class Box
        {
            public int Height { get; set; }
            public int Width { get; set; }

            public Box(int h, int w)
            {
                Height = h;
                Width = w;
            }
            public static Box operator +(Box a, Box b)
            {
                int h = a.Height + b.Height;
                int w = a.Width + b.Width;
                Box res = new Box(h, w);
                return res;
            }
        }

        static void Main(string[] args)
        {
            Box b1 = new Box(14, 3);
            Box b2 = new Box(5, 7);
            Box b3 = b1 + b2;
            Console.WriteLine(b3.Height);
            Console.WriteLine(b3.Width);
        }

底下範例中,實現多載 operator +, operator -, operator *, operator /

Continue Reading

C# Readonly - 教學筆記 (使用visual studio)

readonly與常數用法很像, 相較於常數,readonly通常會用在class流程設計 readonly 在建構子指派值之後,就不能更改

readonly可以在建構子裡面修改

Continue Reading

C# Math, String, Array, Datetime 類別 - 教學筆記 (使用visual studio)

在這裡記錄一些常用的 C# 內置的靜態類別

Continue Reading

C# 解構子 Destructors - 教學筆記 (使用visual studio)

前面我們有提到,只要class被實例化(instantiated),當下就會立即執行建構子 而這裡要說明的解構子(destructor),也是在class被實例化時,會被執行

解構子,具有下列特性: - 一個class只能有一個解構子 - 會在class執行完成,準備結束時自動被調用 - 無法被呼叫 - 不接受修飾符及參數

Continue Reading

C# get & set 存取子(accessors) - 教學筆記 (使用visual studio)

C# get & set 存取子 class的屬性(Property)可以讓讀、寫、運算機制變得更有彈性, 在這裡要介紹屬性的一個特殊的methods,稱為: 存取子(accessors),也可稱為訪問器 存取子包含 get存取子、set存取子

Continue Reading

C# 建構子 (Constructors) - 教學筆記 (使用visual studio)

C# 建構子 Constructors 說明 建構子是一個特殊的Method成員, 只要class被實例化,當下就會立即執行建構子(自動被調用)

在C#中,建構子的名稱必須和class一致,並且不需要定義類型 並且,可以傳入參數

Continue Reading

C# 繼承 (Inheritance) - 教學筆記 (使用visual studio)

C# 繼承(Inheritance) Class 說明

物件導向的方便之處在於,可以被拿來重複使用及擴充 例如,今天新增了使用者檢視列表Class 如果在無法更動情況下,想要擴充新增使用者功能 就可以用繼承(Inheritance)的方式 而被繼承的Class,稱之為「基底類別」(Base Class)

但也要特別留意! C#不支援多重繼承 所以,只允許繼承一個「基底類別」(Base Class)

Continue Reading