UWInfo Blog
發表新文章
[Join] | [忘記密碼] | [Login]
搜尋

搜尋意見
文章分類-#Author#
[所有文章分類]
所有文章分類
  • ASP.NET (48)
  • ASP.NET2.0 (15)
  • ASP.NET4.0 (34)
  • JavaScript (49)
  • jQuery (26)
  • FireFox (4)
  • UW系統設定 (3)
  • SQL (39)
  • SQL 2008 (25)
  • mirror (4)
  • SVN (4)
  • IE (9)
  • IIS (20)
  • IIS6 (1)
  • 閒聊 (7)
  • W3C (6)
  • 作業系統 (9)
  • C# (24)
  • CSS (12)
  • FileServer (1)
  • HTML 5 (11)
  • CKEditor (3)
  • UW.dll (13)
  • Visual Studio (16)
  • Browser (8)
  • SEO (1)
  • Google Apps (3)
  • 網站輔助系統 (4)
  • DNS (5)
  • SMTP (4)
  • 網管 (11)
  • 社群API (3)
  • SSL (4)
  • App_Inventor (1)
  • URLRewrite (2)
  • 開發工具 (6)
  • JSON (1)
  • Excel2007 (1)
  • 試題 (3)
  • LINQ (1)
  • bootstrap (0)
  • Vue (3)
  • IIS7 (3)
  • foodpanda (2)
  • 編碼 (2)
  • 資安 (3)
  • Sourcetree (1)
  • MAUI (1)
  • CMD (1)
  • my sql (1)
最新回應
  • Newtonsoft.Json.JsonConvert.DeserializeObject 失敗的情況
    test...more
  • dotnet ef dbcontext scaffold
    ...more
  • [ASP.NET] 利用 aspnet_regiis 加密 web.config
    ...more
  • IIS ARR (reverse proxy) 服務安裝
    ...more
  • [錯誤訊息] 請加入 ScriptResourceMapping 命名的 jquery (區分大小寫)
    ...more
  • 用 Javascript 跨網頁讀取 cookie (Cookie cross page, path of cookie)
    ...more
  • 線上客服 - MSN
    本人信箱被盜用以致資料外洩,是否可以請貴平台予以協助刪除該信箱之使用謝謝囉...more
  • 插入文字到游標或選取處
    aaaaa...more
  • IIS 配合 AD (Active Directory) 認証, 使用 .Net 6.0
    太感謝你了~~~你救了我被windows 認證卡了好幾天QQ...more
  • PostgreSQL 的 monitor trigger
    FOR EACH ROW 可能要改為 FOR EACH STATEMENT ...more
標籤
  • 918
  • utf8
  • sln
  • structure
  • SSl
  • expression
  • pG2rL0AN
  • tls
  • missor
  • vs
  • UW
  • vb
  • login
  • Rf
  • U2
  • JoBSPKYZ
  • Vue
  • ORM
  • async
  • web.config
  • amazone
  • Cache
  • enum
  • rc4
  • c
  • dictionary
  • profiler
  • CROS
  • innerhtml
  • html,
  • html5
  • date[t]
  • pw
  • pg
  • ad
  • JQ
  • fb
  • dddd
  • findindex
  • ddd
  • EN
  • bluk
  • Image
  • .
  • egs
  • wacs
  • SU
  • Doug
  • -1290
  • sp_
頁數 1 / 6 下一頁
搜尋 aspx 結果:
sessionStorage 跨分頁無法讀取
問題:
在開出新分頁後,無法讀取 sessionStorage 的資料


可能原因:
Chrome 某個版本,Stop cloning sessionStorage for windows opened with noopener
a标签_blank默认 rel="noopener" ,所以a标签需要加入rel=“opener” 而才能像window.open("同源页面")这种方式新开的页面会复制之前的sessionStorage


解決方法:
開新分頁前,加入 rel=“opener”參數即可。
例:
<a href="http://..." target="_blank" rel="opener">Link</a>

$(".hlkPrint").click(function () {
    $("form").setPostDataToStorage();

    $("form").attr("rel", "opener");
    $("form").attr("target", "_blank");
    $("form").attr("action", "xxxxx.aspx");
    $("form").submit();
});





參考:
面试官:你确定多窗口之间sessionStorage不能共享状态吗???
More...
Reiko, 2022/12/1 下午 05:57:23
IIS 配合 AD (Active Directory) 認証, 使用 .Net 6.0
環境說明:

AD Server: dc1 (192.168.101.109)
PC: pc110 (192.168.101.110)
PC: pc111 (192.168.101.111)

第一步,把 PC 加入 AD, 這個算是基本操作,網路上說明很多, 就不再截圖了。不過在這裡還是遇到了第一個問題,解決過程請參考另一份文件: https://blog.uwinfo.com.tw/Article.aspx?Id=486

第二步,在 Visual Studio 的測試環境中測試:
一開始是使用 .Net 6.0 來實作,沒想到找到的文件都是 .Net Core 3.1 的,所以先用 .Net Core 3.1 實做了一次,後來改用 .Net 6.0 實作才成功。使用 .Net 6.0 實作的過程如下:

1. 建立一個 MVC 的標準專案: 
 
為了避免憑証問題,所以拿掉了 HTTPS 的設定


2. 改寫 launchSettings.json:
iisSettings 中的 windowsAuthentication 改為 True, anonymousAuthentication 改為 false。如下圖:
 
3. 修改 Program.cs, 加入以下四行指令:
builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);
builder.Services.AddAuthorization();
app.UseAuthentication();
app.UseAuthorization();
(注意: UseAuthentication 要加在 UseAuthentication 之後, VS 2022 應該會提示要新增 using Microsoft.AspNetCore.Server.IISIntegration;)
 
4. 在 HomeController 增加一個 Action, 以讀取驗証資料:

        [Route("GetAuthenticatedUser")]
        [HttpGet("[action]")]
        public IdentityUser GetUser()
        {
            return new IdentityUser()
            {
                Username = User.Identity?.Name,
                IsAuthenticated = User.Identity != null ? User.Identity.IsAuthenticated : false,
                AuthenticationType = User.Identity?.AuthenticationType
            };
        }

        public class IdentityUser
        {
            public string Username { get; set; }
            public bool IsAuthenticated { get; set; }
            public string AuthenticationType { get; set; }
        }
 
5. 啟動時記得要改用 IIS Express (感覺早上花了兩三個小時在為了這個問題打轉):


6. 執行結果:

第三步,在 IIS 中安裝網站:
1. 在安裝 IIS 時,記得要勾選 windows 驗證


2. 安裝 .Net 6.0 的 Hosting Bundle
https://dotnet.microsoft.com/en-us/download/dotnet/6.0
 
3. 新增網站:
主機名稱留空白 (AD 驗証在網域內好像不會使用指定的主機名稱,這個有待後續再做確認)


如果沒有刪除預設網站,會遇到警告,直接確認即可.


要把 Default Web Site 關閉,再啟動測試站
 
要啟動 windows 驗証: 
在 web.config 中增加 
      <security>
        <authentication>
          <anonymousAuthentication enabled="false" />
          <windowsAuthentication enabled="true" />
        </authentication>
      </security>



修改 applicationHost.config:

檔案位置: %windir%\system32\inetsrv\config\applicationHost.config
這兩地方的 Deny 改為 Allow
<section name="anonymousAuthentication" overrideModeDefault="Deny" />
<section name="windowsAuthentication" overrideModeDefault="Deny" />

 
參考文件: https://docs.microsoft.com/zh-tw/iis/get-started/planning-for-security/how-to-use-locking-in-iis-configuration

3. 可以取得登入資訊如下:

4. 從 Domain 中另一台主機來存取,不用登入,自動取得目前登入者的資訊。
 
5. 從非網域主機連線: 會要求認証
 

目前遇到問題: 在網域中的電腦只能用主機名稱登入,非網域的電腦,才能夠使用網址登入。

測試專案下載: https://github.com/bikehsu/AD60
 
More...
Bike, 2022/3/19 下午 09:10:08
前端處理網址組網址工具
在後端部分,因為有uw元件,在處理url時已經很好處理了
但是在JavaScript因為我們沒有固定js在使用,
因此提供一套簡易使用網址處理工具
thisPage.ParameterByName(key) //取得網址上特定參數
thisPage.OriUrl(key) //中間一段提供修改變數的功能


    <script>
        var thisPage = {
            Init: function () {
                thisPage.InitPageInput();

                $("body")
                    ;
                thisPage.ChangeEvent();
            },
            ParameterByName: function (targetKey) {
                var res = null;
                const urlSearchParams = new URLSearchParams(window.location.search);
                const params = Object.fromEntries(urlSearchParams.entries());
                for (const [key, value] of Object.entries(params)) {
                    if (targetKey.trim().toLocaleLowerCase() === key) {
                        res = value;
                    }
                }
                return res;
            },
            OriUrl: function () {
                var arrayUrl = [];
                arrayUrl.push(window.location.protocol);//https:
                arrayUrl.push("//");
                arrayUrl.push(window.location.hostname);//blog.uwinfo.com.tw
                if (window.location.port.length > 0) {
                    //大多情況,不用特別指定port
                    arrayUrl.push(":");
                    arrayUrl.push(window.location.port);//80
                }
                arrayUrl.push(window.location.pathname);//post/Edit.aspx
                //換一套寫法
                //arrayUrl.push(window.location.search);//?Id=321
                const urlSearchParams = new URLSearchParams(window.location.search);
                const params = Object.fromEntries(urlSearchParams.entries());
                var ayyarQueryString = [];
                //這邊可以加工增加額外的key值
                for (const [key, value] of Object.entries(params)) {
                    if (value.trim().length > 0) {
                        //這邊要注意中文需要encode
                        ayyarQueryString.push(key + "=" + encodeURIComponent(value));
                    }
                }
                if (ayyarQueryString.length > 0) {
                    arrayUrl.push("?");
                    arrayUrl.push(ayyarQueryString.join('&'));
                }
                return arrayUrl.length > 0 ? arrayUrl.join('') : '';
            },
            InitPageInput: function () {
                const urlSearchParams = new URLSearchParams(window.location.search);
                const params = Object.fromEntries(urlSearchParams.entries());
                for (const [key, value] of Object.entries(params)) {
                    $('input[name=' + key + ']').val(value);
                    //這邊因為input有多種不同輸入方式,可以自行編輯
                    //$('select[name=' + key + ']').val(value);
                    //$('textarea[name=' + key + ']').html(value);
                }
            },
            ChangeEvent: function () {

            },
        }
        $(function () {
            thisPage.Init();
        });
    </script>
More...
Doug, 2021/10/1 下午 12:19:30
設定輸出 Header 中的 Content -Type
以下這個可以用在 global.asax 中, 但若是執行到了 aspx 就無效了.
        HttpContext.Current.Response.Headers.Add("Content-Type", "application/json; charset=utf-8");

在 aspx.cs 中, 指定 ContentType 要用以下的方式
        Response.ContentType = "application/json; charset=utf-8";
More...
Bike, 2019/8/15 上午 11:02:00
[教育訓練] 關於 session
1. Asp.Net Session 會造成 Block
2. ashx 和 aspx 在 Session 的預設值是不同的.
3. Clinet 的非同步和 Session 造成的 block 的差異
4. 靜態物件也會互相等待(Browser concurrent connetion 的限制, Edge:8個 Connection, Chrome: 6 個, 2019/4 的測試)
5.ashx 和 aspx 的 session 閞關方式.
6. asp.net 的 session 是看 Cookie, 嘗試做 session hijack

額外追加: 服務的三個 Level(告知, 陪同完成, 詢問並給予進一步的建議)
More...
Bike, 2019/5/2 下午 02:41:33
比較程式碼
以前年輕不懂事, 寫了一些很遜的程式碼, 例如:

舊的程式碼:

        public static DataTable DTFromSQL(string Sql, string DBC = null, Int32 timeout = 0)
        {
            SqlDataAdapter DA = new SqlDataAdapter(Sql, GetDBC(DBC));

            DataTable DT = new DataTable();
            try
            {
                DA = new SqlDataAdapter(Sql, DBC);
                if (timeout > 0)
                {
                    DA.SelectCommand.CommandTimeout = timeout;
                }

                DA.Fill(DT);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                DA.Dispose();
            }

            return DT;
        }


新的程式碼:
        public static DataTable DTFromSQL(string Sql, string DBC = null, Int32 timeout = 30)
        {
            using (var DA = new SqlDataAdapter(Sql, GetDBC(DBC)))
            {
                //不可為 null
                DataTable DT = new DataTable();

                DA.SelectCommand.CommandTimeout = timeout;

                DA.Fill(DT);

                return DT;
            }
        }


可以參考:
https://dotblogs.com.tw/yc421206/archive/2012/01/03/64154.aspx
 
More...
Bike, 2018/4/4 上午 07:56:39
LINE Pay介接
LINE Pay款流程: 
reserve Page(紅科) 發送 reserve API => 取得 payment URL => 轉址到 payment URL => LINE Pay 檢查USER狀態 => 轉回confirm page(紅科), 發送 confirm API => DOWN.

付款需要程式: 
reserve API, confirm API:

send request JSON and read return JSON:
C#: 
using System.Net;
using System.IO;

public partial class TEST : System.Web.UI.Page
{
    DB.OrderMain oOrderObj = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        //Setting request header
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("__APIRootURL__");
        httpWebRequest.ContentType = "application/json; charset=UTF-8";
        httpWebRequest.Method = "POST";
        httpWebRequest.Headers.Add("X-LINE-ChannelId", DB.SysConfig.LINEPay.ChannelId);
        httpWebRequest.Headers.Add("X-LINE-ChannelSecret", DB.SysConfig.LINEPay.SecretKey);

        //加入參數
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string requestJSON = "{\"productName\": \"" + DB.SysConfig.SYSTEM_NAME + "\"," +
                                "\"productImageUrl\": \"" + DB.SysConfig.URL_Shopping + "images/Logo.jpg\"," +
                                "\"amount\": " + oOrderObj.TotalAmount() + "," +
                                "\"currency\": \"TWD\"," +
                                "\"orderId\": \"" + oOrderObj.DisplayOrderId + "\"," +
                                "\"confirmUrl\": \"" + DB.SysConfig.URL_Shopping + "Handler/LinePay/GotoComfirm.aspx?Id=" + oOrderObj.Id + "\"," +
                                "\"cancelUrl\": \"" + DB.SysConfig.URL_Shopping + "Shopping/OrderComplete.aspx?Id=" + oOrderObj.Id + "\"," +
                                "\"capture\": \"true\"," +
                                "\"confirmUrlType\": \"CLIENT\"}";

            streamWriter.Write(requestJSON);
            streamWriter.Flush();
            streamWriter.Close();
        }

        //取得回覆資訊
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        //解讀回覆資訊
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseJSON = streamReader.ReadToEnd();
            //將 JSON 轉為物件
            GN.LinePay.reserveRes.ReturnJSON oReturnObj = (GN.LinePay.reserveRes.ReturnJSON)Newtonsoft.Json.JsonConvert.DeserializeObject(responseJSON, typeof(GN.LinePay.reserveRes.ReturnJSON));

            if (oReturnObj.returnCode == "0000")
            {
                //成功
            }
            else
            {
                //失敗
                string ErrMsg = "Error Code: " + oReturnObj.returnCode + "\r\n" + oReturnObj.returnMessage;
            }
        }
    }
}


.vb
Imports System.Net
Imports System.IO

Partial Class TEST
    Inherits System.Web.UI.Page

    Dim oOrderObj As DB.OrderMain
    Private Sub Admin_TEST_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Setting request header
        Dim httpWebRequest As HttpWebRequest = WebRequest.Create("__APIRootURL__")
        httpWebRequest.ContentType = "application/json; charset=UTF-8"
        httpWebRequest.Method = "POST"
        httpWebRequest.Headers.Add("X-LINE-ChannelId", DB.SysConfig.LINEPay.ChannelId)
        httpWebRequest.Headers.Add("X-LINE-ChannelSecret", DB.SysConfig.LINEPay.SecretKey)
        '加入參數
        Using streamWriter As New StreamWriter(httpWebRequest.GetRequestStream())
            Dim requestJSON As String = "{""productName"": """ + DB.SysConfig.SYSTEM_NAME + """," +
                                        """productImageUrl"": """ + DB.SysConfig.URL_Shopping + "images/Logo.jpg""," +
                                        """amount"": " + oOrderObj.TotalAmount() + "," +
                                        """currency"": ""TWD""," +
                                        """orderId"": """ + oOrderObj.DisplayOrderId + """," +
                                        """confirmUrl"": """ + DB.SysConfig.URL_Shopping + "Handler/LinePay/GotoComfirm.aspx?Id=" + oOrderObj.Id + """," +
                                        """cancelUrl"": """ + DB.SysConfig.URL_Shopping + "Shopping/OrderComplete.aspx?Id=" + oOrderObj.Id + """," +
                                        """capture"": ""true""," +
                                        """confirmUrlType"": ""CLIENT""}"

            streamWriter.Write(requestJSON)
            streamWriter.Flush()
            streamWriter.Close()
        End Using
        '取得回覆資訊
        Dim httpResponse As HttpWebResponse = httpWebRequest.GetResponse
        '解讀回覆資訊
        Using streamReader As New StreamReader(httpResponse.GetResponseStream())
            Dim responseJSON As String = streamReader.ReadToEnd()
            '將 JSON 轉為物件
            Dim oReturnObj As GN.LinePay.reserveRes.ReturnJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(responseJSON, GetType(GN.LinePay.reserveRes.ReturnJSON))

            Dim ResMsg As String = ""
            If oReturnObj.returnCode = "0000" Then
                '成功

            Else
                '失敗
            End If
        End Using
    End Sub
End Class




工具網站:
JSON 轉物件 http://json2csharp.com/
C# to VB : http://converter.telerik.com/



#專案: 紅科
More...
Reiko, 2017/6/21 下午 07:22:58
windows 2008R2 大量工作排程的匯出備份以及匯入
由於工作排程往往有數十個甚至百來個 因此需要一個方法能快速備份及移轉到其他 server 的方法
查了一下,好像也只能這樣做

---- 使用指令把全部排程匯出 ----
參考網址
https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

schtasks /query /XML > all_tasks.xml  
schtasks /query /FO CSV /V >sched_tasks.csv

** xml 比較有用,可以用來匯入到其他server排程,但還要額外處理才能匯入
** csv 只是用來看看目前有哪些排程 可以用來做報表看看
** 這些是全部排程,還要特別處理把 Microsoft 及其他軟體建的排程移除

--------------------------------------------------------------

----如何匯入工作排程到其他 server --------

** 需再寫程式把 all_tasks.xml 拆解成所有排程的單一 xml
   並且生成指令 bat

** 注意 xml 必須是 UTF-16 (unicode) 
   因為 "schtasks /query /XML > all_tasks.xml"產生 xml 是 ansi 

參考網址
https://serverfault.com/questions/325569/how-do-i-import-multiple-tasks-from-a-xml-in-windows-server-2008
** /TN "排程名稱" --- 排程名稱可以是路徑名 
D:\>schtasks.exe /create /TN "\2016JOB\Global\CountryMonthlyStats" /XML "D:\one_task.xml"
** 下面程式碼只是下面程式碼只是參考 還沒實作過
=====================================

var taskXML = new XmlDocument();
taskXML.Load(@"d:\temp\schedtasksBackup.xml");
var batbody = new StringBuilder();

XmlNodeList tasks = taskXML.DocumentElement.GetElementsByTagName("Task");

string strFileName = "d:\\temp\\Task";

for (int i = 0; i < tasks.Count; i++) {
    string onetaskXML = tasks[i].OuterXml;

    //Create the New File. With a little more extra effort
    //you can get the name from a comment above the task -> 應該把註解裡的名稱抓出
    XmlWriter xw = XmlWriter.Create(strFileName + "_" + (i+1) + ".xml");
    batbody.AppendLine(string.Format("schtasks.exe /create /TN \"{0}\" /XML \"{1}\"", "Task " + (i+1) + " Name", strFileName + "_" + (i+1) + ".xml"));

    //Write the XML
    xw.WriteRaw(onetaskXML.ToString());
    xw.Close();

    // Write a bat to import all the tasks
    var batfile = new System.IO.StreamWriter("d:\\temp\\importAllTasks.bat");
    batfile.WriteLine(batbody.ToString());
    batfile.Close();

}
=====================================

#微軟的排程備份真是有夠爛沒有辦法用介面一鍵搞定


More...
darren, 2017/5/5 下午 12:07:30
還原資料庫後不用刪除帳號再新增的方法 (SQL User)
先在 Server 上面建立好同名的帳號, 然後可以用這個指令

sp_change_users_login 'Auto_Fix', 'username'


若想要連 Server 上的帳號一併建立: 

sp_change_users_login [ @Action = ] 'action'
    [ , [ @UserNamePattern = ] 'user' ]
    [ , [ @LoginName = ] 'login' ]
    [ , [ @Password = ] 'password' ]
[;]

[ @Action= ] 'action'
描述此程序所要執行的動作。 動作是varchar (10)。 通常是 'Auto_Fix'

[ @UserNamePattern= ] 'user'
這是目前資料庫中的使用者名稱。 使用者是sysname,預設值是 NULL。
[ @LoginName= ] 'login'
這是 SQL Server 登入的名稱。 登入是sysname,預設值是 NULL。
[ @Password= ] 'password'
指派給新的密碼SQL Server藉由指定建立登入Auto_Fix。 如果符合的登入已經存在,對應的使用者和登入和密碼會被忽略。 如果符合的登入不存在,則 sp_change_users_login 會建立新SQL Server登入,並指派密碼當做新登入的密碼。 密碼是sysname,而且不可以是 NULL。


參考: https://msdn.microsoft.com/zh-tw/library/ms174378.aspx
More...
Bike, 2017/1/3 下午 02:25:38
簡單的 HTTP Relay By MVC.
客戶要求
1. 檔案只能放在 Firewall 內的後台用 Web server (Server A).
2. 使用者只能存取 DMZ 的 Web server (Server B).
3. Server B 只能用 HTTP 通過 Firewall 向 Server A 要資料.(i.e.  Server B 不能掛戴 Server A 的目錄成為虛擬目錄)

所以在 Server B 上面建立了一支程式用 HTTP 的方式讀取 Server A 的檔案再寫出去.

例如, http://ServerB/Upload/test.pdf 會讀取 http://ServerA/Upload/test.pdf 再送到 Client 端

namespace WWW.Controllers
{
    public class UploadController : Controller
    {
        // GET: Upload
        public void Index(string Filename)
        {
            //Create a stream for the file
            Stream stream = null;

            //This controls how many bytes to read at a time and send to the client
            int bytesToRead = 10000;

            // Buffer to read bytes in chunk size specified above
            byte[] buffer = new Byte[bytesToRead];

            string url = "http://admin-dev.nanya.bike.idv.tw/newnanyaback/Upload/" + Filename;

            // The number of bytes read
            try
            {
                //Create a WebRequest to get the file
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);

                //Create a response for this request
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;

                //Get the Stream returned from the response
                stream = fileResp.GetResponseStream();

                // prepare the response to the client. resp is the client Response
                var resp = HttpContext.Response;

                if (Filename.ToLower().EndsWith(".png") ||
                    Filename.ToLower().EndsWith(".jpg") ||
                    Filename.ToLower().EndsWith(".jpeg") ||
                    Filename.ToLower().EndsWith(".gif")
                    )
                {
                    resp.ContentType = "image";
                }
                else
                {
                    //Indicate the type of data being sent
                    resp.ContentType = "application/octet-stream";

                    //Name the file
                    resp.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(Filename, Encoding.UTF8) + "\"");
                }

                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

                int length;
                do
                {
                    // Verify that the client is connected.
                    if (resp.IsClientConnected)
                    {
                        // Read data into the buffer.
                        length = stream.Read(buffer, 0, bytesToRead);

                        // and write it out to the response's output stream
                        resp.OutputStream.Write(buffer, 0, length);

                        // Flush the data
                        resp.Flush();

                        //Clear the buffer
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        // cancel the download if client has disconnected
                        length = -1;
                    }
                } while (length > 0); //Repeat until no data is read
            }
            finally
            {
                if (stream != null)
                {
                    //Close the input stream
                    stream.Close();
                }
            }
        }
    }
}



但不是這樣就好了, 在 RouteConfig.cs 中要加上:
            routes.MapRoute(
                name: "Upload",
                url: "Upload/{filename}",
                defaults: new { controller = "Upload", action = "Index", filename = UrlParameter.Optional }
            );

此外在 Web.Config 中也要加上:

  <system.webServer>
    <handlers>
      <add name="UrlRoutingHandler_Upload"
           type="System.Web.Routing.UrlRoutingHandler, 
               System.Web, Version=4.0.0.0, 
               Culture=neutral, 
               PublicKeyToken=b03f5f7f11d50a3a"
           path="/Upload/*"
           verb="GET"/>
    </handlers>
  </system.webServer>

參考:
http://stackoverflow.com/questions/5596747/download-stream-file-from-url-asp-net

http://blog.darkthread.net/post-2014-12-05-mvc-routing-for-url-with-filename.aspx
More...
Bike, 2016/12/1 下午 09:34:30
|< 123456 >|
頁數 1 / 6 下一頁
~ Uwinfo ~