如何将一个URL转发到MVC上的404错误页面

时间:2016-10-21 14:19:00

标签: c# asp.net-mvc web-config

我的mvc应用程序正在使用以下网址:

/Content/ /Content/style.css /Content/image.png

我想为url /Content/创建转发它应转发给404错误。所有其他网址都应该有效。怎么做?

我尝试了以下解决方案,但它将所有文件从/ Content /转发到404错误页面,但我只想阻止主目录。

的Web.config:

<validation validateIntegratedModeConfiguration="false" />
    <handlers>
      ...
      <add name="hideDirectoryContent" verb="*" path="Content" type=" NameSspace.NoAccessHandler"/>
    </handlers>
  </system.webServer>

NoAccesHandler.cs:

public class NoAccessHandler : IHttpHandler
    {

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.StatusCode = 404;
        }

        #endregion
    }

1 个答案:

答案 0 :(得分:0)

要做到这一点,你只需要创建一个如下控制器(在mvc 4上测试)

public class ContentController : Controller
{
    // GET: Content
    [AllowAnonymous]
    public ActionResult Index()
    {
        return new HttpStatusCodeResult(HttpStatusCode.NotFound, "Not Found");
    }
}

并在您的RoutesCollection中使用

routes.RouteExistingFiles = true;

希望这会有所帮助