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
標籤
  • 找不到金鑰
  • .
  • -1948
  • outerhtml
  • message,
  • -8136
  • Line
  • JSON
  • load
  • mod
  • IE11
  • IP
  • 8
  • 16
  • PG
  • net
  • [U2]
  • [t]
  • 9604
  • jquery
  • 防火牆
  • 長時間
  • 長度
  • 鏡像
  • 鎖死
  • 鎖定
  • asp
  • 錯誤 cs0241:
  • 錯誤碼為 -2146
  • bkXLPYQo
  • 金鑰
  • 重複
  • 遠端桌面服務
  • 遠端桌面
  • 遠端[t]
  • 耗時
  • 1602
  • 悟
  • 快取
  • 必須為非負數且小於集
  • 必需
  • aspx212112
  • column
  • 定義
  • 定位
  • 學習
  • 存取被拒
  • 壓力測試
  • 執行緒
  • 在 pdf 加浮水印
頁數 2 / 3 上一頁 下一頁
搜尋 JSON 結果:
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
CORS 實做 (jQuery + ASP.NET Core Web API)
加構獨立的 API Server 時, 要使用 Cookie 認証必需有以下條件:

1. Web Server 和 API Server 有相同的父網域.
2. Cookie 的網域指定到相同的父網域.
3. 在 API 的 Application 中允許 CORS Request, 需要修改 Startup.cs

3.1 在 ConfigureServices 中要加入  AddCors, 而且要記得 AllowCredentials()
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(name: "Cors(PolicyName",
                                 builder =>
                                 {
                                     builder.WithOrigins("https://web1.yourdomain.com",
                                                         "https://web2.yourdomain.com")
                                     .AllowCredentials();
                                 });
            });

            services.AddControllers()
                .AddNewtonsoftJson(opt =>
                 opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());


3.2 在 Configure 中, 要加入 app.UseCors("Cors(PolicyName"), 記得要在  UseAuthorization() 之前.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseExceptionMiddleware();

            app.UseHttpsRedirection();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(MyAllowSpecificOrigins);

            app.UseAuthorization();



4. 在 Client 端要加上 withCredentials: true
                            $.ajax({
                                url: apiRoot + "apiurl",
                                type: 'GET',
                                dataType: 'json', // 預期從server接收的資料型態
                                success: function (res) {
                                    console.log("success: ");
                                    console.log(res);                                    
                                },
                                xhrFields: {
                                    withCredentials: true
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    alert("發生錯誤");
                                }
                            });
More...
Bike, 2021/10/24 下午 05:17:54
奇怪的 alert 問題.. 用 setTimeout 來解決.
以下的程式碼, 直接 alert(this.errorMessages); 會造成 chrome 卡住..
使用  setTimeout 延後 alert 可以解決這個問題. 但必需延後足夠的時間. 已知 200 ms 依然會卡住.

    errorMessages: "",

    failProcess: function (ret) {
        console.log("failProcess start: " + new Date().getSeconds() + "." + new Date().getMilliseconds());
        var json = ret.responseJSON;
        if (json && json.invalidatedPayloads) {
            var errors = json.invalidatedPayloads.filter(function F(x) {
                return x.messages.length > 0
            });

            console.log("bdfore add class: " + new Date().getSeconds() + "." + new Date().getMilliseconds());

            errors.map(function (x) {
                return $("[name='" + x.name + "']").addClass("error");
            });

            console.log("after add class: " + new Date().getSeconds() + "." + new Date().getMilliseconds());

            errorMessages = errors.map(function (x) {
                    return x.messages.join('\r\n');
            }).join('\r\n');

            console.log("afger build errorMessages: " + new Date().getSeconds() + "." + new Date().getMilliseconds());
            console.log(errorMessages);

            //alert(this.errorMessages);

            window.setTimeout(api.alertError, 500);

            console.log("after alert: " + new Date().getSeconds() + "." + new Date().getMilliseconds());
        }

        console.log("failProcess end: " + new Date().getSeconds() + "." + new Date().getMilliseconds());
    },
More...
Bike, 2021/9/29 下午 08:45:07
處理 json 的一些問題
1. ExpandoObject 用 string 為 key 取值時, 必需轉換為 IDictionary 物件.

2. int 類別的欄位, 傳入的 json 中, 相對應的欄位, 不能為 null.

 
More...
Bike, 2020/10/20 上午 08:12:20
在 CentOS 上面啟動多個 .Net Core 的網站
1. 參考這裡設定第一個網站:
https://blog.johnwu.cc/article/centos-asp-net-core-neginx.html
注意, 文章中有一個錯誤:
/etc/nginx/conf.d/my-website.conf 的第 27 行, 應該是 include /etc/nginx/conf.d/default_proxy_settings;

2.  因為要避開 5000 port, 所以修改第二個網站的 appsettings.json, 讓第二個網站開在 5002 port, 如下.
{
"Logging": {
    "LogLevel": {
     "Default": "Information",
     "Microsoft": "Warning",
     "Microsoft.Hosting.Lifetime": "Information"
    }
},
"Kestrel": {
        "EndPoints": {
                "Http": {
                        "Url": "http://localhost:5002"
                }
        }
},
"AllowedHosts": "*"
}


3. 新增 /etc/nginx/conf.d/my-website2.conf, 要注意
    A. portal2
    B. server localhost:5002
    C. server_name coretest2.bike.idv.tw
    當然 SSL 憑証的檔名也要記得改.

upstream portal2 {
    # localhost:5000 改成 ASP.NET Core 所監聽的 Port
    server localhost:5002;
}

server {
    # 只要是透過這些 Domain 連 HTTP 80 Port,都會轉送封包到 ASP.NET Core
    listen 80;
    # 可透過空白區分,綁定多個 Domain
    server_name coretest2.bike.idv.tw;
    location / {
        proxy_pass http://portal2/;
        include /etc/nginx/conf.d/default_proxy_settings;
    }
}

# 用 HTTPS 必須要有 SSL 憑證,如果沒有要綁定 SSL 可以把下面整段移除
server {
    # 只要是透過這些 Domain 連 HTTPS 443 Port,都會轉送封包到 ASP.NET Core
    listen 443 ssl;
    server_name coretest2.bike.idv.tw;
    ssl_certificate /etc/nginx/ssl/coretest2.bike.idv.tw.crt;
    ssl_certificate_key /etc/nginx/ssl/coretest2.bike.idv.tw.key;

    location / {
        proxy_pass http://portal2/;
        include /etc/nginx/conf.d/default_proxy_settings;
    }
}


改完後就可以用了.

以下是 https://blog.johnwu.cc/article/centos-asp-net-core-neginx.html 抄過來的一些檔案, 作為備份:

setup-aspnet-core.sh
#!/bin/bash

main() {
    sudo yum -y install epel-release
    sudo yum -y update

    install_nginx
    install_dotnet

    sudo firewall-cmd --add-service=http --permanent
    sudo firewall-cmd --add-service=https --permanent
    sudo firewall-cmd --reload
}

install_nginx() {
    echo "###################################"
    echo "########## Install Nginx ##########"
    echo "###################################"
    sudo yum -y install httpd-tools nginx
    sudo setsebool -P httpd_can_network_connect on
    sudo sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
    sudo setenforce 0
    sudo systemctl enable nginx
    sudo systemctl restart nginx
}

install_dotnet() {
    echo "###########################################"
    echo "########## Install .NET Core 2.2 ##########"
    echo "###########################################"
    sudo rpm -Uvh https://packages.microsoft.com/config/rhel/7/packages-microsoft-prod.rpm
    sudo yum -y install aspnetcore-runtime-2.2
}

main "$@"


用以下指令執行:
sudo sh setup-aspnet-core.sh



/etc/systemd/system/my-website.service, (/bin/dotnet 有可能是 /usr/bin/dotnet)
[Unit]
# Description=<此服務的摘要說明>
Description=MyWebsite

[Service]
# WorkingDirectory=<ASP.NET Core 專案目錄>
WorkingDirectory=/usr/share/my-website

# ExecStart=/bin/dotnet <ASP.NET Core 起始 dll>
ExecStart=/bin/dotnet MyWebsite.dll

# 啟動若失敗,就重啟到成功為止
Restart=always
# 重啟的間隔秒數
RestartSec=10

# 設定環境變數,注入給 ASP.NET Core 用
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target


服務相關指令:
# 開啟,開機自動啟動服務
systemctl enable my-website.service

# 關閉,開機自動啟動服務
systemctl disable my-website.service

# 啟動服務
systemctl start my-website.service

# 重啟服務
systemctl restart my-website.service

# 停止服務
systemctl stop my-website.service

# 查看服務狀態
systemctl status my-website.service


/etc/nginx/conf.d/default_proxy_settings
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;


/etc/nginx/conf.d/my-website.conf
upstream portal {
    # localhost:5000 改成 ASP.NET Core 所監聽的 Port
    server localhost:5000;
}

server {
    # 只要是透過這些 Domain 連 HTTP 80 Port,都會轉送封包到 ASP.NET Core
    listen 80;
    # 可透過空白區分,綁定多個 Domain
    server_name demo.johnwu.cc example.johnwu.cc;
    location / {
        proxy_pass http://portal/;
        include /etc/nginx/conf.d/default_proxy_settings;
    }
}

# 用 HTTPS 必須要有 SSL 憑證,如果沒有要綁定 SSL 可以把下面整段移除
server {
    # 只要是透過這些 Domain 連 HTTPS 443 Port,都會轉送封包到 ASP.NET Core
    listen 443 ssl;
    server_name demo.johnwu.cc;
    ssl_certificate /etc/nginx/ssl/demo.johnwu.cc_bundle.crt;
    ssl_certificate_key /etc/nginx/ssl/demo.johnwu.cc.key;

    location / {
        proxy_pass http://portal/;
        include /etc/nginx/conf.d/default_proxy_settings;
    }
}


Nginx 重新啟動:
# 檢查 Nginx 的設定是否有誤
nginx -t

# 若沒有錯誤,即可套用
nginx -s reload
More...
Bike, 2020/7/7 上午 08:01:43
設定輸出 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
[U2] SQL 物件也有 GetPageDT2 了哦.
使用範例如下:


    void getList()
    {
        var Q = TN.Admin.TCatOrderDeliveryRecord.Select().OrderBy("DeliveryCompletion_Date, Id Desc");

        if (U2.WU.IsNonEmptyFromQueryStringOrForm("OD00"))
        {
            Q.And("OD00 = ", U2.WU.GetValue("OD00"));
        }

        if (U2.WU.V.StartDate_IsOK)
        {
            Q.And("DeliveryCompletion_Date >= ", U2.WU.V.StartDate);
        }

        if (U2.WU.V.EndDate_IsOK)
        {
            Q.And("DeliveryCompletion_Date < ", U2.WU.V.EndDate);
        }

        U2.JSON.WriteSuccessData(Q.GetPageDT2(U2.WU.V.CurrentPage, U2.WU.V.PageSize));
    }
More...
Bike, 2019/5/30 上午 12:02:46
bootstrap-formhelpers intlTelInput 套件注意的問題
A下拉霸
 <div class="col-md-6">
                                        <label for="contact:fromlan">Source Language <span class="red">*</span></label>
                                        <div class="bfh-selectbox" data-name="From_Language_Id" id="FromLanItemParent">
                                            <!--FromLanItem S-->
                                            <div data-value="{Id}"><img src="assets/images/_smarty/flags/{Image}" alt="{Abbreviation}"> {LanguageName}</div>
                                            <!--FromLanItem E-->
                                        </div>
                                    </div>

自動生成的下拉霸
1 name 要用 data-name=""來設定
2 完全沒有選擇的時候可能會回傳空值

套件來源
http://bootstrapformhelpers.com/select/

B電話號碼
<label for="contact_department">Your Phone Number </label>
                                        <div>
                                            <input id="phone" name="phone" type="tel">

                                        </div>
                                        <div style="display:none">
                                            <input id="PhoneCountry" name="PhoneCountry" type="">
                                        </div>


                                        <script src="/assets/build/js/intlTelInput.js"></script>
                                        <script>
                                            var input = document.querySelector("#phone");
                                            var iti1 = window.intlTelInput(input, {
                                                // allowDropdown: false,
                                                // autoHideDialCode: false,
                                                // autoPlaceholder: "off",
                                                // dropdownContainer: document.body,
                                                // excludeCountries: ["us"],
                                                // formatOnDisplay: false,
                                                // geoIpLookup: function(callback) {
                                                //   $.get("http://ipinfo.io", function() {}, "jsonp").always(function(resp) {
                                                //     var countryCode = (resp && resp.country) ? resp.country : "";
                                                //     callback(countryCode);
                                                //   });
                                                // },
                                                // hiddenInput: "full_number",
                                                // initialCountry: "auto",
                                                // localizedCountries: { 'de': 'Deutschland' },
                                                // nationalMode: false,
                                                // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
                                                placeholderNumberType: "MOBILE",
                                                // preferredCountries: ['cn', 'jp'],
                                                separateDialCode: true,
                                                utilsScript: "/assets/build/js/utils.js",
                                            });
                                            input.addEventListener("countrychange", function () {
                                                $('#PhoneCountry').val(JSON.stringify(iti1.getSelectedCountryData()))
                                                // do something with iti.getSelectedCountryData()
                                            });
                                        </script>

需要用另一個欄位來記錄電話號碼的國家資料 

套件的來源
https://github.com/jackocnr/intl-tel-input
 
More...
sean, 2019/3/6 上午 10:41:03
Ajax 的 Content Type
這兩天發現的現象。有點不好找錯,所以紀錄一下
因為制式報名頁面使用 ajax form 物件,但 ios 的 safari 一直發生資料有送出,
但是送出後網頁就不跑success後面的 javascript,例如彈跳訊息及導到下個頁面
一開始debug的方向有點猜錯,所以花了點時間找問題
後來才注意到,原來他跑到 ajax error去了,不是 ajax success
直覺可能是 ContentType 的問題,因為預設是 text/html
結果 Response.ContentType 改 application/x-javascript, 就過了  (WTF)
我猜 application/json 應該也沒問題吧
------------------------------
經查證: application/json 比較正確 



 
More...
darren, 2018/8/2 下午 12:33:16
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
|< 123 >|
頁數 2 / 3 上一頁 下一頁
~ Uwinfo ~