顯示具有 ASP.NET WebForm 標籤的文章。 顯示所有文章
顯示具有 ASP.NET WebForm 標籤的文章。 顯示所有文章

2021年6月4日 星期五

Views

API 傳值和回傳

 目的:練習使用json.html和json.aspx發出ajax請求,並使用json.ashx(沒有畫面的api)返回json物件格式


1.json.html語法

<!DOCTYPE html>
    <head >
        <title>JSON</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>                        
    </head>
<body>
    <H5>Hwllo World</H5>

    <script>
    $.ajax({
        url: "json.ashx",
        data: {"id":"0125","name":"Tina"},
        type: "POST",
        dataType: "json",
        success: function(returnData){
            console.log(returnData);
        },
        error: function(xhr, ajaxOptions, thrownError){
            console.log(xhr.status);
            console.log(thrownError);
        }
    });

    </script>
</body>
</html>

$.ajax各屬性代表意思
(1).請求ashx檔案的時候 要把contentType去掉,還有就是
data 格式為 {”key”,”value”};切記 不要再 大括號外面加雙引號,這樣就會在ashx頁面取不到資料而失敗。
(2).
contentType
contentType是網頁要送到Server的資料型態,若沒指定則預設為'application/x-www-form-urlencoded; charset=UTF-8'
dataType
dataType是網頁預期從Server接收的資料型態,若沒指定則jQuery會根據response的MIME type來推定為xml, json, script, html, text。

2.json.aspx語法code behind要有json.aspx.cs就不放上

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Template.aspx.cs" Inherits="Template" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
    <title>Ch2</title>
<title>Bootstrap Navigation Bar</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>                     
</head>

<body >
<h1>This is Empty</h1>

<form runat="server">

</form>


<script>


$.ajax({
    url: "json.ashx",
    data: {"id":"0125","name":"Tina"},
    type: "POST",
    dataType: "json",
    success: function(returnData){
        console.log(returnData);
    },
    error: function(xhr, ajaxOptions, thrownError){
        console.log(xhr.status);
        console.log(thrownError);
    }
});


</script>

</body>
</html>

3.調用json.ashx的API


<%@ WebHandler Language = "C#" Class = "ResponseOds" %>
using System;
using System.Web;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

public class ResponseOds : IHttpHandler
{
	
    public void ProcessRequest (HttpContext context)
    {
        
        string id=context.Request["id"]; //接到前端傳來值
        if(id=="0125") //判斷是0125的值,在將相對應要回傳值丟到前台
        {
            List<Student> lstStuModel = new List<Student>()
            {
                new Student(){ID=1,Name="張飛",Age=250,Sex="男"},
                new Student(){ID=2,Name="潘金蓮",Age=300,Sex="女"}
            };

            //Newtonsoft.Json序列化
            string jsonData = JsonConvert.SerializeObject(lstStuModel);

            context.Response.ContentType = "application/json"; //回傳json格式
            context.Response.Charset = "utf-8";
            context.Response.Write(jsonData);
        }

        
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }



    class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public string Sex { get; set; }
    }

參考資料 (1).(2).(3).

2021年4月2日 星期五

Views

ASP.NET 前後端取值

 1.下拉選單

  前端:

  <select name="Dog">

  <option>請選擇你最愛的寵物</option>

    <option value="1">Dog</option>

    <option value="2">Cat</option>

</select>

  後端:

  (Request.Form["Dog"]??string.Empty)

2021年3月2日 星期二

Views

ASP.NET JS註冊事件

 1.

string myScript = @"function AlertHello() { alert('Hello ASP.NET');}"
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"MyScript", myScript, true);
第一個參數:使用型別(註冊腳本控制項類型,是控制項還是this的GetType()都可以,typeOf(string)也沒問題)/第二個參數為「腳本函數的名稱」也就是腳本函數的名字,根據實現的功能起名字/第三個參數為 腳本內容。需要注意的是第3個參數是js腳本內容,每一條語句結束加分號/第四個參數標明是否再添加腳本標籤,如果第四個參數裡包含了<script></script>標籤,此處則為false,否則為true
js註冊在ASP.NET頂部產生但在<form>標籤下面
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="O11Y7RGYEvejqiRRay4zlxPQxo2jyMqMAbHJAf3OjJ3684yRvLWVBqhIEeQA/+qEtJ/hKirLH3lNHd8EXGCwPIpKmQqMIySj+uovrEhpvzP/jlHFBZpZTK9ruoq7n1zL">
</div>
<script type=”text/javascript”>
<!–
function AlertHello() { alert(‘Hello ASP.NET’); }// –>
</script>


2.
string myScript = @"alert(document.forms[0]['TextBox1'].value);";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"MyScript", myScript, true);
js註冊在ASP.NET底部產生但在</form>標籤上面
<script type="text/javascript">
//<![CDATA[
alert(document.forms[0]['TextBox1'].value)//]]>
</script>
</form>

補充:RegisterStartupScript 方法添加的腳本塊在頁面加載完成但頁面的 OnLoad 事件引發之前執行。

原文網址:https://kknews.cc/code/ypp6kek.html

3.
string myScript = "myJavaScriptCode.js";
Page.ClientScript.RegisterClientScriptInclude(“myKey”, myScript);
JS註冊在在ASP.NET頂部產生但在<form>標籤下面
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="ZgyuLcK8bB0p+BqVpP/lBFj726mrglK0SUUom02SQjfi1TlAD88592F2B1lX55wA/MnY+TFLYuiKzLdKPGRCbo4509nsJuunc+AdZ4nPwz62nkQhK4TlvpzK7lLttOw2">
</div>
<script src="myJavaScriptCode.js" type="text/javascript"></script>

2020年5月18日 星期一

Views

抓取Repeater內部的控制項

因為資料只有三筆,所以Items[0]表示第一列以此類推

前端:Code

 <div>
 <asp:Repeater id="rpt" runat="server">
      <headertemplate>
            <table>
      </headertemplate>
            <itemtemplate>
                <tr>
                <td>
                <asp:CheckBox ID="cb" Value='<%# Eval("id") %>' Text='<%# Eval("name") %>' runat="server"/>
                <asp:TextBox ID="txt" runat="server" Visible='<%# Eval("bool").ToString()=="T"?true:false %>'/>
                </td>
                </tr>
            </itemtemplate>
       <footertemplate>
            </table>
       </footertemplate>
 </asp:Repeater>
 </div>

後端:可以寫個按鈕直接打出來

TextBox txt = (TextBox)rpt.Items[2].FindControl("txt");

表示抓取第三列第二個TextBox值,因為資料只有三筆,其中隱藏第二個TextBox

2020年5月16日 星期六

Views

[ASP.NET 資安專區] 弱點掃描修正

1. ASP.NET debugging enabled
    why:因為沒有關掉黃頁,導致網頁錯誤資訊會曝光
    solution:在位置為system.web下方,將debug模式關掉
    <system.web>
              <compilation debug="false"/>
               <customErrors mode="RemoteOnly" defaultRedirect="500.htm">
                 <error statusCode="500" redirect="~500.htm"/>
     </system.web>

2. Clickjacking:X-Frame-Options header missing
    why:X-Frame-Options HTTP 回應標頭 (header) 用來指示文件是否能夠載入 <frame>, <iframe> 以及 <object>,網站可以利用 X-Frame-Options 來確保本身內容不會遭惡意嵌入道其他網站、避免 clickjacking 攻擊
    solution:設定IIS 請加入以下指令到網站的 Web.config 檔:

    <system.webServer>
     <httpProtocol>
          <customHeaders>
          <add name="X-Frame-Options" value="SAMEORIGIN" />
          </customHeaders>
     </httpProtocol>
    </system.webServer>
    參考文獻

3.ASP.NET version disclosure
  why:ASP.NET 版本揭露,對於網站是不必要的揭露資訊
  solution:APPly the following changes to the web.config file to prevent ASP.NET wersion disclosure
  <System.Web>
       <httpRuntime enableVersionHeader="false">
  </Sustem.Web>

4.SQL injection 注意所有http gte/post 都要防止惡意字串被惡意注入東西,所以後端接收參數改寫要注意

2020年5月14日 星期四

Views

使用APP_Code資料夾的方法

例如方法名稱為MyFun

namespace MyFun
{
    public class Add
    {
        public static int Math(int number)
        {
            return number+1;
        }
    }

    public class Write
    {
        public static string Name()
        {
            return "Trista";
        }
    }
    
}

在aspx.cs檔使用方式為:
可直接在Page_Load那邊呼叫
protected void Page_Load(object sender,EventArgs e)
{
   Response.Write(MyFun.Add.Math(1)+MyFun.Write.Name());
}