發表文章

目前顯示的是有「ASP.NET」標籤的文章

ASP.NET MVC 實作301轉址 含(.NET CORE)

圖片
 ASP.NET MVC 實作 301永久轉址 302暫時轉址 ASP.NET MVC 內建的都是  RedirectResult  和  RedirectActionResult  和  RedirectToRouteResult  都是基於302轉向 301和302的轉向差別在於會不會把流量轉移以及舊網址的SEO (Search Engine Optimization) SEO是搜尋引擎針對網站的各項指標的優化所作的綜合評分  理論上來講是不太會需要去分別這兩個之間的差距,除非你是認真的想要衝搜尋排名。 301轉址實作 1. 使用 Implicit Action Result 將 Action 的回傳型別改成 void public void Redirect1() {     Response.StatusCode = 301;     Response.AppendHeader("Location", Url.Action("About")); } 2. 使用內建的 EmptyResult 回應 public ActionResult Redirect2() {     Response.StatusCode = 301;     Response.AppendHeader("Location", Url.Action("About"));     return new EmptyResult(); } 於 Startup.cs 的  Configure()中新增 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {     var options = new RewriteOptions()         .AddRewrite("Post.aspx", "api/Post", skipRemainingRules: true)         .AddRedirect("Pos...

.NET 建立加密ZIP

 之前有一篇是  走訪資料夾及Web下載檔案(zip)  這篇 主要使用的是  ZipArchive   System.IO.Compression 名命空間裡提供一個類別 ZipArchive 但是這個類別有一個問題 那就是無法加密。 接著因為工作需求,老闆叫我搞一個加密的,因此有了這篇文章 主要還是依照  走訪資料夾及Web下載檔案(zip)  的概念 但是這次使用的是DotNetZip static void Main(string[] args)         {             //目前抓前一天 可修改             DateTime Start = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00.000"));             DateTime End = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59.999"));             List<model> lsResponse = ModelData();             string nasPath = ConfigurationManager.AppSettings["nasPath"];             string xmlPath = ConfigurationManager.AppSettings["xmlPath"];             //目前數量 控管在2000內        ...

//新的Excel寫法#2

 //新的Excel寫法#2 public Task<string> CommonWriteExcel<TData>(List<TData> dataList,Dictionary<string,string>reportHeader) {     var dataObject = JsonConvert.SerializeObject(dataList);     DataTable table = JsonConvert.DeserializeObject<DataTable>(dataObject);     using( var ms = new MemoryStream())     {         IWorkbook workbook = new XSSFWorkbook();         ISheet excelSheet = workbook.CreateSheet("Sheet1");         List<String> columns = new List<string>();         IRow row = excelSheet.CreateRow(0);         int columnIndex = 0;         foreach (System.Data.DataColumn column in table.Columns)         {             if (reportHeader.Keys.Contains(column.ColumnName))             {  ...

//新的Excel寫法#1

 //新的Excel寫法#1 public void ExcelCreate<T>(List<T> lsT , string savePath, XSSFWorkbook workbook = null, string SheetName = "預設頁面", string DataName = null             , bool overwrite = false)         {             //檢查workbook null則建立             if (workbook == null){                 workbook = new XSSFWorkbook();                 workbook.CreateSheet(SheetName);             }             //複寫 => 刪除後新增             if (overwrite == true)                 workbook.RemoveName(SheetName);             //若 Sheet為null 建立CreateSheet             if (workbook.GetSheet(SheetName) == null)     ...

ASP.NET WebForm 圖形驗證碼生成技術

需求 產生一個圖形驗證碼,要可以換圖形驗證碼,並且阻止更換圖形驗證碼時刷新頁面。 畫圖需要  using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D;  private string CreateRandomNum(int NumCount)     {         //建立陣列 也可以直接用for迴圈塞入         string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";         string[] allCharArray = allChar.Split(',');//差分成陣列                    string randomNum = ""; //亂數組成的string         int temp = -1;//記錄上次亂數值的數值,儘量避免產生幾個相同的亂數         Random rand = new Random();         for (int i = 0; i < NumCount; i++)         {             if (temp != -1)             {                  //依照時間戳記給Random種子,         ...

C# ASP.NET Code-Behind 呼叫JS

假設前端有一個 JS 前端 <script> function test(input){     alert(input); } </script> 後端 ScriptManager.RegisterClientScriptBlock(this, GetType(), "Button popup", "xalert('Welcome to Taiwan!');", true); 如果檢視原始碼,會發現 RegisterClientScriptBlock 那段會轉成 <script type="text/javascript"> //<![CDATA[ xalert('Welcome to Taiwan!');//]]> </script> 這是2017年的程式碼了,我這邊目前沒有建ASP.NET的環境,只有ASP.Net MVC 跟 ASP.NET Core 參考: https://blog.xuite.net/tolarku/blog/533226152

System.IO.File.Delete引發的路徑存取被拒錯誤

之前在工作的時候遇到 當下了System.IO.File.Delete()這段code之後無法執行刪除,顯示了如標題所示。 英文錯誤訊息 An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll Additional information: Access to the path 'C:\YourOwnPath' is denied. 上網查了之後 有三種可能 第一種 路徑是否正常? 而我的路徑是直接帶變數,因此沒有錯的理由 第二種 網站存取檔案的身分是否正常? 我當初是使用管理員權限開啟,因此也沒有問題 第三種 刪除用同一個身分建立的檔案出錯 這個要確定是否由該身分建立的 接著思考之後發現這三個都不太可能,因為我是用DeBug模式去跑的網站,因此有可能就是他說的另一個問題,檔案屬性設定問題。 因此在刪除之前重新設定屬性就是處理方法。 System.IO.File.SetAttributes("C:\YourOwnPath\YourFileName.ext", System.IO.FileAttributes.Normal); System.IO.File.Delete("C:\YourOwnPath\YourFileName.ext"); 參考: http://slashview.com/archive2020/20201110.html

iTextSharp 使用 以Excel 建立 PDF

這是一個從2000年左右就開始在使用的函式庫,用於畫一個PDF出來。 現代應該都是用Word套版另存新檔變成PDF 用的應該是匯出PDF 但是假如你家的Office是低於等於2007版本(有一個版本之後才能直接另存新檔成PDF) 那你就得 手刻 大概 public ActionResult PDF(HttpPostedFileBase file) {                //建立文件 用於建立PDF             Document doc = new Document();             //從直行變橫             doc.SetPageSize(doc.PageSize.Rotate());             //建立MemoryStream             MemoryStream ms = new MemoryStream();             //取得相對 根路徑 用於儲存xls檔案進入目標位置用於讀取               //這邊讀取的是Excel             string pathXls = Server.MapPath("~/xls");             try             {                 //若path不存在,建立      ...

判斷Checkbox是否被勾選(含多個選項)及全選

當初要判斷這個的原因是因為前端使用了Razor自動產生了一排的同ID的 <input id = 'CheckAll' type = 'CheckBox' name = 'CheckAll' value = '全選'> @foreach (var item in ItemList){      <input id="Data" type='checkbox' name='Data' value='@item.Value'>@item.Text } 這樣會自動產生 ItemList.Length 個 id為Data的checkbox 通常一般的做法判斷checkbox是否被勾選是使用 $('#Data').prop('checked'); 假如他是true 則代表勾選,false則代表沒有勾選 並且不可以使用 $('#Data').attr('checked'); 這個判斷會顯示undefined 而這時候我想要的判斷是,我想要判斷 是否有其中任何一個被選擇 ? 因此我使用下列判斷 $('input[id="Data"]:checked').length != 0 $('input[id="Data"]:checked')這個判斷是顯示所有id為Data且被Check的 而.length則是判斷是否有被選取的選項(判斷是否有被選取) 如何一次取得多個CheckBox的值 <script type="text/javascript">         function show() {             obj = document.getElementsByName("Data");             check_value = [];             for (i in obj) {                 if (obj[i].checked)     ...

GridView 建立以及後端如何取得資料 如何取得隱藏值

<asp:GridView runat="server" ID="GrvMap" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC"                 BorderStyle="None" BorderWidth="1px" CellPadding="3" EnableModelValidation="True" OnRowDeleting="GrvMap_RowDeleting">                 <Columns>                          <%-- 各種Columns... --%>                     <asp:BoundField DataField="UserCompID" />                     <asp:TemplateField HeaderText="刪除">                         <ItemTemplate>                             <asp:Button runat="server" Text="刪除" OnClientClick="return confirm('確定刪除?')...

判斷檔案是否存在、開檔寫及存Excel以及特殊存取ajax回傳值

public ActionResult Query(HttpPostedFileBase[] files)         {           //取得路徑 路徑為IIS的根目錄下的Temp 不管發佈在哪             string path = HttpContext.Server.MapPath("../Temp/");             //判斷是否存在資料夾,不存在則建立             if (!System.IO.Directory.Exists(path))             {                 System.IO.Directory.CreateDirectory(path);             }             //走訪回傳資料             try             {                 foreach (HttpPostedFileBase file in files)                 {                     //獲取Path,取IIS根目錄,並串起新newPath       ...

Controller 獲得 View的幾個方法

有稍微幾種語法 第一種是常用的ajax $.ajax({     type:"POST",     data:data //data可以先自行包東西進去 通常是包個json進去     //data:{  data:"data" , bata:"bata" }     //Url: @Url.Action("Action" , "Controller"), //Razor     //Url:"Controller/Action", //MVC     Url:"URL", }); 大致上是這樣 還可以用error 或者success 之類的東西測試成功失敗 第二種是直接用OnClick 裡面也算是透過Razor的部分 <button ... onclick="window.open('@Url.Action("Action" , "Controller" ,  new { target = "_blank" , count = 1})')"> 後面的new {...} 裡面的值會自動轉換成?... 也就是變成 ?count=1&...的型態 第三種是MVC的功能 @using (Html.BeginForm("Action" , "Controller")){     //是一個Razor提供的方法 用Submit可以把目前頁面View的Model回傳至後端 } 以上三種應該都能用Public ActionResult Action(){return View();}接 而由於MVC系列的Model會自動對上,因此後端地接收回傳值甚至可以寫個Model去接他 只要裡面屬性的名字跟回傳值有對上就好 如data:{data:"999"} 那Model如果裡面有 data的話 就可以呼叫 Model.data 得到會是999 補充方法 1.  /* HTML section */ <html>   ..........     <button...