从 Mvc 路由返回错误的 http 状态代码
我有一个 asp.net mvc 路由,它获取一个 url 并执行简单的获取并从请求返回状态代码。
<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)并转到 url http://www.facebook.com/blah .html,我得到了预期的 404 返回。但是,如果我使用我的应用程序通过 ajax 调用来调用 mvc 路由,我会得到 200。如果我将请求对象的 AllowAutoRedirect 设置为 false,我会得到 302。我从未得到 404。我正在通过 Firebug 再次验证这一点。谁能指出我做错了什么?
谢谢!
I have a asp.net mvc route that is taking a url and doing a simple get and return the status code from the request.
<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
Now if I use firefox (using Firebug) and go to the url http://www.facebook.com/blah.html, I get the expected 404 returned. However if I use my application to call the mvc route via an ajax call, I get 200. If I set the request object's AllowAutoRedirect to false, I get 302. I never get a 404. I am verifying this once again through Firebug. Can anyone point out what I am doing wrong?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 FaceBook,请确保您设置了用户代理,否则站点会将您重定向到标准 HTML 页面,解释您的操作(因此会出现 200 状态代码):
此外,当从 HttpWebRequest 返回的状态代码不同于 200 时,也会出现异常将抛出,更具体地说是 WebException。因此,您需要捕获此 WebException 并在 < a href="http://msdn.microsoft.com/en-us/library/system.net.webexception.response.aspx" rel="nofollow">Response 属性包含 HttpWebResponse 您将找到 404 StatusCode。
另外,我可能会使用 WebClient 来简化代码:
在客户端:
If you use FaceBook make sure you set the user agent or the site will redirect you to a standard HTML page explaining you to do so (thus the 200 status code):
Also when a status code different than 200 is returned from the HttpWebRequest an exception will be thrown, and more specifically a WebException. So you need to trap this WebException and inside the Response property containing the HttpWebResponse you will find the 404 StatusCode.
Also I would probably use a WebClient to simplify the code:
And on the client: