我有一个asp.net mvc路由,它接受一个url并做一个简单的get并从请求中返回状态代码。
<AcceptVerbs(HttpVerbs.Post)> _
Public Function ValidateUrlStatusCode(ByVal url As String) As ActionResult
Dim code As Integer = 0
Try
Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
request.Method = "GET"
request.AllowAutoRedirect = True
Using response As HttpWebResponse = request.GetResponse
response.Close()
code = response.StatusCode
End Using
Catch ex As Exception
code = HttpStatusCode.InternalServerError
End Try
Return Content(code, "text/plain")
End Function
现在,如果我使用firefox(使用Firebug)并转到网址http://www.facebook.com/blah.html,我会收到预期的404返回。但是,如果我使用我的应用程序通过ajax调用调用mvc路由,我得到200.如果我将请求对象的AllowAutoRedirect设置为false,我得到302.我从来没有得到404.我再次通过Firebug验证这一点。谁能指出我做错了什么?
谢谢!
答案 0 :(得分:1)
如果您使用FaceBook,请确保设置用户代理,否则该网站会将您重定向到标准HTML页面,向您解释(因此200状态代码):
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";
当从HttpWebRequest返回状态代码不同于200时,将抛出异常,更具体地说是WebException。因此,您需要捕获此WebException并在包含Response的HttpWebResponse属性中找到404 StatusCode。
此外,我可能会使用WebClient来简化代码:
Public Function ValidateUrlStatusCode(url As String) As ActionResult
Dim code = 0
Try
Using client = New WebClient()
client.Headers(HttpRequestHeader.UserAgent) = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"
Dim response = client.DownloadString(url)
End Using
Catch ex As WebException
Dim httpResponse = TryCast(ex.Response, HttpWebResponse)
If httpResponse IsNot Nothing Then
code = CInt(httpResponse.StatusCode)
End If
End Try
Return Content(code.ToString(), "text/plain")
End Function
在客户端:
<script type="text/javascript">
$.ajax({
url: '@Url.Action("ValidateUrlStatusCode")',
type: 'POST',
data: { url: 'http://www.facebook.com/blah.html' },
success: function (result) {
alert(result);
}
});
</script>