返回401 HTTP错误状态代码

时间:2014-11-10 16:20:02

标签: ajax asp.net-mvc url http-headers

最近我将我的网站从AJAX更新为ASP.MVC5,因此需要删除仍在搜索引擎中的旧网址。

由于我的旧网址是基于AJAX的,因此Google不会自行删除它们,因为每个旧网址都会重定向到主页,例如:

mysite.com/#!product/phone/samsung/galaxy3
mysite.com/#!product/phone/iphone/ip4s
mysite.com/#!product/phone/nokia/lumia920

现在,每当服务器收到旧网址(包含#!_escaped_fragment_

的请求时,解决方案就会向Google返回401 HTTP错误状态

如何在MVC5中主动将此401 HTTP错误状态代码返回给requester?非常感谢!

3 个答案:

答案 0 :(得分:1)

您需要创建路线。在路线中写RedirectLocation并返回Status

public class NewUrlRoute : RouteBase
      {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
          const string status = "401 HTTP error status";
          var request = httpContext.Request;
          var response = httpContext.Response;
          var title = "";
          var legacyUrl = request.Url.ToString();
          var newUrl = "";
          var id = request.QueryString.Count != 0 ? request.QueryString[0] : "";

          if (legacyUrl.Contains(" #!"))
          {
            response.Status = status;
            response.RedirectLocation = "newUrl";
            response.End();
          }
            return null;
        }

      }

答案 1 :(得分:1)

如果您想在控制器中实现此功能,您只需检查以前的网址,然后执行以下操作:

HttpContext.Response.StatusCode = 401;

无论您的返回类型如何,路由引擎都会自动处理响应标头。

答案 2 :(得分:0)

解决了,原来有一种非常简单的方法:.NET MVC-4 routing with custom slugs

    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var url = requestContext.HttpContext.Request.Path.TrimStart('/');


        if (!string.IsNullOrEmpty(url))
        {
            if (url.Contains("_escaped_fragment_"))
                requestContext.HttpContext.Response.StatusCode = 401;
            else
                requestContext.HttpContext.Response.StatusCode = 404;

            FillRequest("Error","Index", requestContext);
        }

        return base.GetHttpHandler(requestContext);
    }

通过这种方式,我甚至可以实现404 custom error page,我之前没有任何运气而挣扎(下面的代码不起作用,上面的代码确实如此):

        // Add this code to handle non-existing urls
        routes.MapRoute(
            name: "404-PageNotFound",
            // This will handle any non-existing urls
            url: "{*url}",
            // "Shared" is the name of your error controller, and "Error" is the action/page
            // that handles all your custom errors
            defaults: new { controller = "Error", action = "Index" }