模擬動作比較麻煩,實務上這個需求我們是會在程式裡組一個 HTTP POST 送給目標的 action url後同樣在程式裡取回內容。(實際上你在表單填完的東西按下送出,瀏覽器也是幫你把它們組成 HTTP POST 送給 action url,再解析 Server 吐回來的內容成結果畫面給你看)
核心程式
string _GetWebResponse(string url, NameValueCollection parameters) { // following line is to make sure when https certificate isn't valid the method will still work ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.Method = "POST"; var sb = new StringBuilder(); foreach (var key in parameters.AllKeys) sb.Append(key + "=" + parameters[key] + "&"); sb.Length = sb.Length - 1; byte[] requestBytes = Encoding.UTF8.GetBytes(sb.ToString()); httpWebRequest.ContentLength = requestBytes.Length; using (var requestStream = httpWebRequest.GetRequestStream()) { requestStream.Write(requestBytes, 0, requestBytes.Length); requestStream.Close(); } Task<WebResponse> responseTask = Task.Factory.FromAsync<WebResponse>( httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, null); using (var responseStream = responseTask.Result.GetResponseStream()) { var reader = new StreamReader(responseStream); return reader.ReadToEnd(); } }url 為目標 action url 網址、parameters 為 form 裡參數的 key、val 組合(比如 input 的 name 跟 val),並以字串形式回傳結果,本例會用 json,如果你取的是 HTML 你可能還會需要 HTML parser。
使用上是類似這樣
// replace to ur target form parameters NameValueCollection nvc = new NameValueCollection(); nvc.Add("Account", "acc123"); nvc.Add("Password", "acc123"); // replace to ur target action url string url = Url.Action("JsonRes", "Home", null, Request.Url.Scheme); string ret = _GetWebResponse(url, nvc); //var tmp = JsonConvert.DeserializeObject(ret); return Json(ret, JsonRequestBehavior.AllowGet);
如果還不清楚可以到 Git 載範例(為MVC5,不過_GetWebResponse(...) 是 WebForm 也通用的)。
ref: StackOverFlow 、 暗黑執行緒(解決目標為 https 問題)
沒有留言:
張貼留言