考虑重定向的ASP.NET Web API服务
public class ThisController : ApiController
{
/* more methods */
public override HttpResponseMessage Post()
{
var result = new HttpResponseMessage(HttpStatusCode.MovedPermanently);
// Post requests should be made to "ThatController" instead.
string uri = Url.Route("That", null);
result.Headers.Location = new Uri(uri, UriKind.Relative);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
试图验证POST数据到"api/this"会将你重定向到"api/that",我有以下测试方法:
[TestMethod]
public void PostRedirects()
{
using (var client = CreateHttpClient("application/json"))
{
var content = CreateContent(expected, "application/json");
using (var responseMessage = client.PostAsync("api/this", content).Result)
{
Assert.AreEqual(HttpStatusCode.MovedPermanently, responseMessage.StatusCode);
Assert.AreEqual(new Uri("https://api.example.com/api/that"), responseMessage.Headers.Location);
}
}
}
protected HttpClient …Run Code Online (Sandbox Code Playgroud) 使用WebClient类,我可以轻松地获得网站的标题:
WebClient x = new WebClient();
string source = x.DownloadString(s);
string title = Regex.Match(source,
@"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>",
RegexOptions.IgnoreCase).Groups["Title"].Value;
Run Code Online (Sandbox Code Playgroud)
我想存储URL和页面标题.但是,当遵循以下链接时:
我显然想要将我重定向到的Url.
质询
有没有办法在WebClient课堂上这样做?
我怎么用HttpResponse和HttpRequest?
该应用程序使用client.PostAsync()发送帖子.我希望它不要遵循302重定向.
怎么样?
我想我可以AllowAutoRedirect按照这个答案中的描述进行设置.
但是如何HttpWebRequest在PostAsync()调用中使用?