使用this question的最佳答案,我可以成功提交登录表单并使用WebClient获取经过身份验证的网页:
var loginCredentials = new NameValueCollection
{
{ "username", "user123" },
{ "password", "pass321" },
};
client.UploadValues(
@"http://www.mywebsite.com/User/Login?ReturnUrl=" +
@"http://www.mywebsite.com/Tickets/Search", loginCredentials);
但是,当我尝试在结果网页上提交另一个表单来搜索特定的过滤器(一个是“下拉”元素,另一个是“选项”元素)时,我对方法UploadValues感到遗憾:
var jitbitSearch = new NameValueCollection
{
{ "fromUserId_username", "447" },
{ "statusId", "-3" },
};
try
{
client.UploadValues(
@"http://www.mywebsite.com/Tickets/Search", jitbitSearch);
}
catch {}
string result = client.DownloadString("http://www.mywebsite.com/Tickets/Search");
textBox1.Text = result;
fromUserId_username 的HTML输出(下拉菜单):
<td><script type='text/javascript' src='/js/jquery.autocomplete.js'></script> <input type="text" id="fromUserId_username" name="fromUserId_username" value="" placeholder="Email or user" />
<input type="hidden" id="fromUserId" name="fromUserId" value="" />
<script type="text/javascript">
$(function() {
InitUserBox('fromUserId', "");
});
</script>
statusId 的HTML输出(选择选项):
<td>Status:</td>
<td><select name="statusId">
<option value=""></option>
<option value="10" >Undergoing</option>
<option value="5" >Under analysis</option>
<option value="2" >Pending</option>
<option value="6" >On hold</option>
<option value="3" >Closed</option>
<option value="1" >Under testing</option>
<option value="4" >New</option>
<option value="7" >Under development</option>
<option value="8" >Recurring</option>
<option value="">--------</option>
<option value="-10" style="color:#CC6666;">(not) Undergoing</option>
<option value="-5" style="color:#CC6666;">(not) Under analysis</option>
<option value="-2" style="color:#CC6666;">(not) Pending</option>
<option value="-6" style="color:#CC6666;">(not) On hold</option>
<option value="-3" style="color:#CC6666;">(not) Closed</option>
<option value="-1" style="color:#CC6666;">(not) Under testing</option>
<option value="-4" style="color:#CC6666;">(not) New</option>
<option value="-7" style="color:#CC6666;">(not) Under development</option>
<option value="-8" style="color:#CC6666;">(not) Recurring</option>
</select>
知道导致异常的是什么吗?是因为UploadValues方法不支持这种输入吗?感谢。
注意:即使我注释掉其中一个表单输入,它们都会触发webexception。
编辑:我得到的例外情况如下: “远程服务器返回错误:(500)内部服务器错误”。
答案 0 :(得分:1)
回答我的问题,做这个小改动对我有用:
byte[] request = client.UploadValues(@"http://www.mywebsite.com/Tickets/Search", "POST", jitbitSearch);
string req = Encoding.UTF8.GetString(request);
textBox1.Text = req;