例如,我有一个网页(ASP.NET MVC),在其中可以获取某些资源的cookie。
我的MVC控制器操作代码:
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
string data = "<Request><MsgType>Authenticate</MsgType><SubMsgType>Login</SubMsgType><UserID>MYLOGIN</UserID><passwordNotEncrypted>MYPASSWORD</passwordNotEncrypted></Request>";
StringContent content = new StringContent(data, Encoding.UTF8, "text/xml");
HttpClient client = new HttpClient(handler);
Uri uri = new Uri("https://address/browserservices.aspx/login");
HttpResponseMessage response = client.PostAsync(uri, content).Result;
此请求将auth cookie设置为cookies
变量。下一个请求可以正常工作:
var result = client.GetAsync("https://address/RemoteSupport.aspx?id=bla-bla-bla&pltFrmType=Android&agentversion=13.46").Result;
var text = result.Content.ReadAsStringAsync().Result;
(如果我在不使用Cookie的情况下调用它,则会收到Unauthorized
响应)
现在,我想使用Cookie重定向到此https://address/RemoteSupport.aspx?id=bla-bla-bla&pltFrmType=Android&agentversion=13.46
地址。因此,用户应查看将其重定向到该地址。怎么做?
我尝试过:
foreach (Cookie cookie in responseCookies)
{
Response.Cookies.Append(cookie.Name, cookie.Value);
}
return Redirect($"https://address/RemoteSupport.aspx?id={id}&pltFrmType=Android&agentversion=13.46");
但不起作用
答案 0 :(得分:0)
您不能仅执行重定向。在MVC中,它向浏览器返回302状态代码,指示其向第三方网站提出自己的请求。
使用HttpClient
的相同实例,您需要向第三方服务器发出第二个请求。这将自动将cookie添加到新请求中,然后您可以格式化答案并将其传递给浏览器客户端。
理想情况下,您不应在方法中实例化HttpClient,因为这意味着您每次必须发出2个请求。也许是这样的:
public class MyController : Controller
{
private static readonly HttpClient _httpClient;
public MyController()
{
if (_httpClient == null)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
_httpClient = new HttpClient(handler);
LoginWithClient();
}
}
private void LoginWithClient()
{
string data = "<Request><MsgType>Authenticate</MsgType><SubMsgType>Login</SubMsgType><UserID>MYLOGIN</UserID><passwordNotEncrypted>MYPASSWORD</passwordNotEncrypted></Request>";
StringContent content = new StringContent(data, Encoding.UTF8, "text/xml");
Uri uri = new Uri("https://address/browserservices.aspx/login");
HttpResponseMessage response = client.PostAsync(uri, content).Result;
// Maybe check the result here, but we should have the cookie by now
}
public JsonResult MyAction()
{
var result = client.GetAsync("https://address/RemoteSupport.aspx?id=bla-bla-bla&pltFrmType=Android&agentversion=13.46").Result;
var text = result.Content.ReadAsStringAsync().Result;
return Json(text, JsonRequestBehavior.AllowGet);
}
这应该将原始文本字符串返回到浏览器,您可以在其中显示它,或者将其解析为Json或XML或其他任何形式并使用数据。