12

在 MVC 5.2.2 中,我可以设置Routes.AppendTrailingSlash为 true 以便将斜杠附加到 url。

但是我也有一个机器人控制器,它返回 robots.txt 的内容。

如何防止将斜杠附加到 robots.txt 路由并使其在没有尾部斜杠的情况下可调用?

我的控制器代码:

[Route("robots.txt")]
public async Task<ActionResult> Robots()
{
  string robots = getRobotsContent();
  return Content(robots, "text/plain");
}

我的路线配置如下所示:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home",
                                action = "Index",
                                id = UrlParameter.Optional }
            );

RouteTable.Routes.AppendTrailingSlash = true;
4

2 回答 2

10

动作过滤器怎么样。我写得很快,不是为了效率。我已经针对我手动放置和引导“/”的 URL 对其进行了测试,并且工作起来就像一个魅力。

    public class NoSlash : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var originalUrl = filterContext.HttpContext.Request.Url.ToString();
            var newUrl = originalUrl.TrimEnd('/');
            if (originalUrl.Length != newUrl.Length)
                filterContext.HttpContext.Response.Redirect(newUrl);
        }

    }

尝试以这种方式使用它

   [NoSlash]
   [Route("robots.txt")]
   public async Task<ActionResult> Robots()
   {
       string robots = getRobotsContent();
       return Content(robots, "text/plain");
    }
于 2015-04-14T17:25:09.910 回答
2

如果导航到静态 .txt 文件,则 ASP.NET 的行为是在 URL 有斜杠时返回 404 Not Found。

我采用了@Dave Alperovich 的方法(谢谢!)并返回一个 HttpNotFoundResult 而不是重定向到没有斜杠的 URL。我认为这两种方法都是完全有效的。

/// <summary>
/// Requires that a HTTP request does not contain a trailing slash. If it does, return a 404 Not Found.
/// This is useful if you are dynamically generating something which acts like it's a file on the web server.
/// E.g. /Robots.txt/ should not have a trailing slash and should be /Robots.txt.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class NoTrailingSlashAttribute : FilterAttribute, IAuthorizationFilter
{
    /// <summary>
    /// Determines whether a request contains a trailing slash and, if it does, calls the <see cref="HandleTrailingSlashRequest"/> method.
    /// </summary>
    /// <param name="filterContext">An object that encapsulates information that is required in order to use the <see cref="System.Web.Mvc.RequireHttpsAttribute"/> attribute.</param>
    /// <exception cref="System.ArgumentNullException">The filterContext parameter is null.</exception>
    public virtual void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        string url = filterContext.HttpContext.Request.Url.ToString();
        if (url[url.Length - 1] == '/')
        {
            this.HandleTrailingSlashRequest(filterContext);
        }
    }

    /// <summary>
    /// Handles HTTP requests that have a trailing slash but are not meant to.
    /// </summary>
    /// <param name="filterContext">An object that encapsulates information that is required in order to use the <see cref="System.Web.Mvc.RequireHttpsAttribute"/> attribute.</param>
    protected virtual void HandleTrailingSlashRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpNotFoundResult();
    }
}
于 2015-04-22T08:36:21.853 回答