我必须实现一个自定义 HttpModule 来处理 Sharepoint 中的 404 错误.
I had to implement a custom HttpModule to handle a 404 error in Sharepoint.
它侦听 PreSendRequestContent 事件,并查找 404 状态代码.如果找到,则执行 TransferRequest.
It listens for the PreSendRequestContent event, and looks for a 404 status code. If one is found it does a TransferRequest.
void App_PreSendRequestContent(object sender, EventArgs e) { HttpResponse res = App.Response; HttpRequest req = App.Request; if (res.StatusCode == 404 && !req.Url.AbsolutePath.Equals(PageNotFoundUrl, StringComparison.InvariantCultureIgnoreCase)) { App.Server.TransferRequest(PageNotFoundUrl); } }这很好用,但我在 Fiddler 中注意到页面显示 200 状态代码,即使原始请求是 404.这对搜索引擎不利.
This works just fine, but I noticed in Fiddler that the page is showing a 200 status code, even though the original request was a 404. This is not good for search engines.
这是 传输请求?我可以以某种方式维护 404 状态代码吗?或者,我最好使用老式的 Server.Transfer 吗?
Is this an expected behaviour of TransferRequest? Can I somehow maintain the 404 status code? Or, would I have been better off using a good old fashioned Server.Transfer?
更新
我在共享点环境之外尝试了这个,Server.TransferRequest 请求确实给出了 200 状态代码,删除了 404.Server.Transfer 不起作用,因为我认为它不能提供管道.
I tried this outside of a sharepoint environment, and the Server.TransferRequest request does indeed give a 200 status code, removing the 404. Server.Transfer doesn't work as I don't think it can given the pipeline.
更新 2
感谢下面的回答,我添加了以下内容:
Thanks to the answer below, I have added the following:
void App_PostRequestHandlerExecute(object sender, EventArgs e) { HttpResponse res = App.Response; HttpRequest req = App.Request; if (req.Url.AbsolutePath.Equals(PageNotFoundUrl, StringComparison.InvariantCultureIgnoreCase)) { res.StatusCode = 404; } } 推荐答案好吧,TransferRequest() 触发一个新的请求,这意味着一个新的响应.由于PageNotFoundUrl 指向的资源确实存在,客户端会收到一个合法的200 OK 状态标头.
Well, TransferRequest() triggers a new request, which implies a new response. Since the resource that PageNotFoundUrl points to does exist, the client receives a legitimate 200 OK status header.
您可能想要编写一个 HTTP 处理程序(或处理 Global.asax) 以便在服务 PageNotFoundUrl 时强制状态标头为 404 Not Found.
You might want to write an HTTP handler (or handle an event in Global.asax) in order to force the status header to 404 Not Found when serving PageNotFoundUrl.
更多推荐
Server.TransferRequest() 和 http 状态码
发布评论