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
標籤
  • 58
  • feed
  • 0
  • 98
  • ajax
  • js UNION A
  • web
  • pg21211211
  • user_login
  • egs
  • aspnet
  • 1
  • db
  • Find
  • LINE
  • 50
  • for
  • download
  • google
  • ef
  • 54
  • let
  • C#
  • Rf
  • C#[t]
  • -1023
  • vb ORDER B
  • checkboxli
  • 20
  • iis
  • 考試
  • There is
  • url
  • code
  • openExtern
  • C
  • Server Err
  • list
  • ASCII
  • [t]
  • s3
  • vslerp
  • cros
  • JSON
  • 找不到金鑰
  • .
  • -1948
  • outerhtml
  • message,
  • -8136
頁數 1 / 4 下一頁
搜尋 web. 結果:
.Net 6 的 Captcha 實做
產生 FileStreamResult 物件的 function 如下: (目前置於 SU 之中,以便轉移)

        static List<Brush> CaptchaBrushes = null;
        public static FileStreamResult CreateCaptcha(string captcha)
        {
            if (CaptchaBrushes == null)
            {
                CaptchaBrushes = new List<Brush>();
                CaptchaBrushes.Add(Brushes.White);
                CaptchaBrushes.Add(Brushes.Gold);
                CaptchaBrushes.Add(Brushes.LightSkyBlue);
                CaptchaBrushes.Add(Brushes.LimeGreen);
                CaptchaBrushes.Add(Brushes.AliceBlue);
                CaptchaBrushes.Add(Brushes.AntiqueWhite);
                CaptchaBrushes.Add(Brushes.BurlyWood);
                CaptchaBrushes.Add(Brushes.Silver);
            }

            int width = 90;
            int height = 45;

            //https://stackoverflow.com/questions/61365732/cannot-access-a-closed-stream-when-returning-filestreamresult-from-c-sharp-netc
            //Using statements close and unload the variable from memory set in the using statement which is why you are getting an error trying to access a closed memory stream.You don't need to use a using statement if you are just going to return the result at the end.

            //這個 memory stream 不用關閉或 dispose
            var ms = new MemoryStream();

            // 釋放所有在 GDI+ 所佔用的記憶體空間 ( 非常重要!! )
            using (Bitmap _bmp = new Bitmap(width, height))
            using (Graphics _graphics = Graphics.FromImage(_bmp))
            using (Font _font = new Font("Courier New", 24, FontStyle.Bold)) // _font 設定要出現在圖片上的文字字型、大小與樣式
            {
                // (封裝 GDI+ 繪圖介面) 所有繪圖作業都需透過 Graphics 物件進行操作
                _graphics.Clear(Color.Black);

                // 如果想啟用「反鋸齒」功能,可以將以下這行取消註解
                //_graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

                // 將亂碼字串「繪製」到之前產生的 Graphics 「繪圖板」上
                var x = 10;
                for(var i = 0; i < captcha.Length; i++)
                {
                    _graphics.DrawString(captcha.Substring(i, 1), _font, CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], x, Su.MathUtil.GetRandomInt(15));
                    x += 10 + Su.MathUtil.GetRandomInt(10);
                }

                // 畫線
                
                _graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
                    Su.MathUtil.GetRandomInt(0, Convert.ToInt32((width * 0.9 / 2))), 0, Su.MathUtil.GetRandomInt(Convert.ToInt32(width / 2), Convert.ToInt32(width * 1.9 / 2)), height);
                
                _graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
                    Su.MathUtil.GetRandomInt(Convert.ToInt32(width / 2), Convert.ToInt32(width * 1.9 / 2)), 0, Su.MathUtil.GetRandomInt(0, Convert.ToInt32((width * 0.9 / 2))), height);
                
                _graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
                    0,
                    Su.MathUtil.GetRandomInt(height / 2),
                    width,
                    height / 2 + Su.MathUtil.GetRandomInt(height / 2)
                    );

                _graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
                 0,
                 height / 2 + Su.MathUtil.GetRandomInt(height / 2),
                 width,
                    Su.MathUtil.GetRandomInt(height / 2)
                 );

                _bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            ms.Seek(0, SeekOrigin.Begin);

            // Controller 的型別為 FileResult
            return new FileStreamResult(ms, "image/jpeg")
            { FileDownloadName = $"{DateTime.Now.Ymdhmsf()}.jpg" };
        }



輸出用的 Controller 和 Action 如下:

namespace Web.Controllers
{
    public class CaptchaController : Controller
    {
        [Route("captcha")]
        public async Task<FileStreamResult> Index()
        {
            //產生 Captcha 並存入 Session 之中。目前是四位數字
            string captcha = (await Ah.ReGetAsync<object>("api/kol/create-captcha-code")).ToString();

            //產生圖檔並回傳 FileStreamResult
            return Su.Wu.CreateCaptcha(captcha);
        }
    }
}
More...
Bike, 2022/9/25 下午 10:03:44
IIS 讓網站 .svn 目錄不被讀取
若網站是使用 SVN update 方式更新網站,為了防止被外部讀取到 /.svn/  目錄內容
要在 web.config 片段加上以下內容

<configuration>
<system.webServer>
     <security>
         <requestFiltering>
            <hiddenSegments>
             <add segment=".svn" />
            </hiddenSegments>
         </requestFiltering>
     </security>
</system.webServer>
</configuration>


git 也是一樣的方式
可以參考此網址
https://www.petefreitag.com/item/823.cfm
 
More...
darren, 2022/7/20 下午 04:58:58
VS 建立虛擬目錄導致HttpHandler重複錯誤
 
於VS Web中建立虛擬目錄,導致Swagger Handler出現重複錯誤
主要原因是因為跟網站與子網站指向同一個資料夾,而父子網站的web.config有繼承關係導致。

解決方式:
1. 前往 根目錄 / .vs / 專案 / config / applicationhost.config

2. 將site中設定的子網站移除或變更虛擬目錄位置

 
3. 回到網頁重新整理就完成囉!

參考: 【茶包射手日記】怪異的web.config HttpHandler重複錯誤
More...
梨子, 2022/7/1 上午 11:57:02
.Net Framework 的檔案檢查機制 Web API 和 MVC 5
我們的目標是在啟動時,掛一個 global filter 來檢查上傳的檔案附檔名,避免上傳未預期的可執行檔。使用 global filter 可以防止程式設計師忘了做檔案檢查,發生危險。我們目前用到的 .Net Framework 有兩個類別,一個是 System.Web.Http.ApiController,另一個是 System.Web.Mvc.Controller,兩個要分開處理。

1. Web API (System.Web.Http.ApiController)
.Net Framework 的 Web API 2 在接收檔案時,必需使用 Request.Content.ReadAsMultipartAsync 把上傳的資料存入 MultipartMemoryStreamProvider 之後再來處理。
範例如下: 
    public class UploadController : ApiController
    {
        public async Task<object> PostFormData()
        {
            var provider = new MultipartMemoryStreamProvider();

            if (! Request.Content.IsMimeMultipartContent())
            {
                return "no file";
            }

            //要注意這裡的 await
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var content in provider.Contents)
            {
                if (content.Headers.ContentDisposition.FileName != null)
                {
                    string localFilename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/"));
                    string filename = HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/" + localFilename);
                    if (System.IO.File.Exists(filename))
                    {
                        System.IO.File.Delete(filename);
                    }

                    using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        var contentStream = await content.ReadAsStreamAsync();
                        await contentStream.CopyToAsync(fileStream);
                        Trace.WriteLine("Save To" + filename);
                    }
                }
            }
            return "OK";
        }
    }


程式碼中有個地方我沒有注意到。我一開始是用 Request.Content.ReadAsMultipartAsync(provider); 把資料讀進 provider,但前方沒有加上 await,造成有時讀不到檔案的情況,再次提醒自己 Async 和 Await 的關係。

直覺的想法是在 filter 中執行一樣的程式碼,不存檔,只要抓出檔名來檢查即可。但這時遇到一個問題 Request.Content.ReadAsMultipartAsync 不能執行兩次,Google 了一陣子,也沒找不到類似 seek(0) 的操作。所以只好自己寫一個暫存的機製。

這裡決定使用 System.Web.HttpContext.Current.Items 來暫存 provider,最後的 OnActionExecutingAsync 結果如下:

        /// <summary>
        /// 檔案檢查
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            Trace.WriteLine("ApiCheckFile OnActionExecutingAsync");

            var request = actionContext.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                return;
            }

            var provider = new MultipartMemoryStreamProvider();
            await request.Content.ReadAsMultipartAsync(provider);

            //把 provider 存入 System.Web.HttpContext.Current.Items 之中,以便在 controller 中再度使用
            System.Web.HttpContext.Current.Items["MimeMultipartContentProvider"] = provider;

            foreach (var content in provider.Contents)
            {
                if (content.Headers.ContentDisposition.FileName != null)
                {
                    var filename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
                    Trace.WriteLine(filename);

                    var ext = System.IO.Path.GetExtension(filename);
                    if (!".jpg,.jpeg,.png".Contains(ext.ToLower()))
                    {
                        throw new Exception("file format error.");
                    }
                }
            }

            return;
        }


而 controller 中的 Action 則改為以下的版本;本版本中,除了把上傳的檔案存檔以外,還有讀取 form data 中其它欄位的範例:

        public async Task<object> PostFormData()
        {
            //改由 HttpContext.Current.Items 中,讀取資料。
            MultipartMemoryStreamProvider provider = (MultipartMemoryStreamProvider)System.Web.HttpContext.Current.Items["MimeMultipartContentProvider"];

            //如果沒有經過 filter,provider會是 null, 這時就要直接由 Request.Content 讀入 provider
            if (provider == null)
            {
                provider = new MultipartMemoryStreamProvider();
                Request.Content.ReadAsMultipartAsync(provider);
            }

            foreach (var content in provider.Contents)
            {
                if (content.Headers.ContentDisposition.FileName != null)
                {
                    string localFilename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
                    Trace.WriteLine("FileName: " + localFilename);
                    Trace.WriteLine("FileName: " + @"~/App_Data/Temp/" + localFilename);
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/"));
                    string filename = HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/" + localFilename);
                    if (System.IO.File.Exists(filename))
                    {
                        System.IO.File.Delete(filename);
                    }

                    using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        var contentStream = await content.ReadAsStreamAsync();
                        await contentStream.CopyToAsync(fileStream);
                        Trace.WriteLine("Save To" + filename);
                    }
                }
                else
                {
                    var contentStream = await content.ReadAsStreamAsync();
                    var reader = new System.IO.StreamReader(contentStream);
                    var data = reader.ReadToEnd();
                    Trace.WriteLine("data: " + data);
                }
            }
            return "OK";
        }


以上是展示 Web Api 的 Filter。

如果是 MVC 的 Controller,就簡單多了,直接讀取 actionContext.HttpContext.Request.Files 裡面各檔案的 FileName 即可。不過也遇到了一個和直覺不同的地方,對 actionContext.HttpContext.Request.Files 居然不能用 foreach 請見下方註解掉的地方。也許是我的用法有問題,如果有人找到可以使用的方法也麻煩告知。

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            Debug.WriteLine("MvcCheckFileFilter OnActionExecuting");
            if (actionContext.HttpContext.Request.Files.Count > 0)
            {
                for (int i = 0; i < actionContext.HttpContext.Request.Files.Count; i++)
                {
                    System.Web.HttpPostedFileBase file = actionContext.HttpContext.Request.Files[i];
                    if (System.IO.Path.GetExtension(file.FileName) != ".jpg")
                    {
                        throw new Exception("file format error.");
                    }
                    Debug.WriteLine(i + "MvcCheckFileFilter OnActionExecuting File type: " + file.FileName.ToString());
                }
            }

            //以下寫法會發生錯誤: 無法將類型 'System.String' 的物件轉換為類型 'System.Web.HttpPostedFileBase'。
            //foreach (HttpPostedFileBase file in actionContext.HttpContext.Request.Files)
            //{
            //    if (System.IO.Path.GetExtension(file.FileName) != ".jpg")
            //    {
            //        throw new Exception("file format error.");
            //    }
            //}
        }


最後是把 filter 掛在 global filter 裡,如下:
Web API Controller 的部份:
在 WebApiConfig.cs 裡加上 config.Filters.Add(new ApiCheckFile()); 見下圖:
 

附帶一提,Register 是在 global.asax 裡被叫用的。微軟的架構常常這樣,硬是拉到另一個目錄的獨立檔案裡,如果 global.asax 沒有這一行,不知所以的人,在 App_Start 裡,建立了一個 WebApiConfig.cs 然後會發現完全沒做用... 見下圖

 
MVC Controller 的部份,
在 FilterConfig.cs 中,加上 filters.Add(new MvcCheckFileFilter()); 如下圖
 

一樣是在 global.asax 中呼叫  FilterConfig.RegisterGlobalFilters,見下圖:

 
不過有趣的地方是,在 global.asax 裡, WebApiConfig.Register 和 FilterConfig.RegisterGlobalFilters 的叫用方法不同,一個是把 function 當作變數,一個是直接呼叫 function, 大家可以比較一下。

附註 1, 關於 OnActionExecutingAsync 和 OnActionExecuting:

Web API 的 filter 中,提供了 OnActionExecutingAsync 和 OnActionExecuting 兩個 method 可以 override ,我實驗的結果是如果兩個 method 都 override 了,只有 OnActionExecutingAsync 會被呼叫。

MVC 的 filter 中,只有 OnActionExecuting 可以 override。
 
More...
Bike, 2022/5/15 上午 10:01:11
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
Visual Studio ashx檔 無出現程式碼的自動完成 (Code intelligence)
2022.06.22
1) 後來發現更新這兩個檔案就可以了
參考來源:
https://docs.microsoft.com/zh-tw/dotnet/framework/install/guide-for-developers

2) 要記得把文字編輯器>副檔名的設定移除
3) 注意web.config 中 targetFramework 的版本 不能太舊
targetFramework ="4.6.1"

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

最近安裝新版的Visual Studio 2022
發現ashx檔案沒有自動排版與程式碼相關名稱可以自動代入
找了一陣子才找到, 使用後發現不會檢查程式是否有錯誤..
但還是紀錄一下

開啟Visual Studio 於選單
工具>選項

文字編輯器>副檔名

 
More...
choco, 2022/2/11 上午 09:10:08
使用FtpWebRequest.ReName實現移動檔案功能
FtpWebRequest類別沒有提供移動檔案的命令,但是可以透過WebRequestMethods.Ftp.Rename達成相同效果的功能。

    FtpWebRequest ftp_Request = null/* TODO Change to default(_) if this is not a reference type */;
    FtpWebResponse ftp_Response = null/* TODO Change to default(_) if this is not a reference type */;
    string str_FtpAct = "XXX";
    string str_FtpPwd = "XXX";

    // Try to create backup folder. If folder already created, resume to backup. 
    try
    {
        ftp_Request = (FtpWebRequest)WebRequest.Create("D:/testfolder/backup");
        ftp_Request.Credentials = new NetworkCredential(str_FtpAct, str_FtpPwd);
        ftp_Request.Method = WebRequestMethods.Ftp.MakeDirectory;
        ftp_Response = ftp_Request.GetResponse();
    }
    catch (WebException ex_Web)
    {
        FtpWebResponse ftp_ResponseEx = ex_Web.Response;
        int int_ErrCode = ftp_ResponseEx.StatusCode;
        // 550: Access is denied, means directory already exist
        if (int_ErrCode != 550)
            Console.WriteLine("Create Folder Failed!");
    }

    try
    {
        ftp_Request = (FtpWebRequest)WebRequest.Create("D:/testfolder/test.txt");
        ftp_Request.Credentials = new NetworkCredential(str_FtpAct, str_FtpPwd);
        ftp_Request.Method = WebRequestMethods.Ftp.Rename;
        ftp_Request.RenameTo = "../testfolder/backup/test.txt";
        ftp_Response = (FtpWebResponse)ftp_Request.GetResponse();
    }
    catch (WebException webex)
    {
        // Get FTP Error code and exception status
        FtpWebResponse ftp_ResponseEx = webex.Response;
        int int_FtpCode = ftp_ResponseEx.StatusCode;
         // Do something
    }


    finally
    {
        if (ftp_Response != null)
            ftp_Response.Close();
    }
More...
高級水冷氣, 2020/8/4 下午 04:02:46
資安的檢測
先寫幾個, 有空再整理.

1. Upload Folder 的執行權限要關閉
2. 在HTTP Header加入X-Frame-Options: DENY或SAMEORIGIN。
3. web.config 的 connection string 和 app setting 要加密
More...
Bike, 2019/6/19 下午 05:53:18
[ASP.NET] 利用 aspnet_regiis 加密 web.config
請用系統管理員身分 開啟 cmd.exe

cd C:\Windows\Microsoft.Net\Framework\v2.0.50727

aspnet_regiis -pef "connectionStrings" "專案路徑"


aspnet_regiis -pef "appSettings" "專案路徑"

* 若出現 'aspnet_regiis'  不是內部或外部命令,可執行的程式或批次檔

先確認iis上專案的Framework版本
cd C:\Windows\Microsoft.Net\Framework\該版本的資料夾

若為v4.0.30319
cd C:\Windows\Microsoft.Net\Framework\v4.0.30319

應該就成功了

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

解密的部分

aspnet_regiis -pdf "connectionStrings" "專案路徑"

aspnet_regiis -pdf "appSettings" "專案路徑"
More...
choco, 2019/5/24 下午 07:06:03
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
|< 1234 >|
頁數 1 / 4 下一頁
~ Uwinfo ~