我在MVC 4中有一个简单的控制器,就像这样。对不起,我是.net的大三学生,也许这很简单?
public class HomeController : BaseController
{
public ActionResult Index()
{
ViewBag.h1 = Resources.Language.HomeH1;
ViewBag.Title = Resources.Language.HomeTitle;
ViewBag.Description = Resources.Language.HomeDescription;
return View();
}
public ActionResult Dataroom()
{
ViewBag.h1 = Resources.Language.DataRoomH1;
ViewBag.Title = Resources.Language.DataroomTitle;
ViewBag.Description = Resources.Language.DataroomDescription;
return View();
}
public ActionResult Consultancy()
{
ViewBag.h1 = Resources.Language.ConsultancyH1;
ViewBag.Title = Resources.Language.ConsultancyTitle;
ViewBag.Description = Resources.Language.ConsultancyDescription;
return View();
}
public ActionResult Services()
{
ViewBag.h1 = Resources.Language.ServicesH1;
ViewBag.Title = Resources.Language.ServicesTitle;
ViewBag.Description = Resources.Language.ServicesDescription;
return View();
}
public ActionResult Contact()
{
ViewBag.h1 = Resources.Language.ContactH1;
ViewBag.Title = Resources.Language.ContactTitle;
ViewBag.Description = Resources.Language.ContactDescription;
return View();
}
当链接正常时它正在工作oK,但是如果someoen进入like / simpleexample等。 我希望用户始终重定向到主页,这是一个简单的修复方法吗?
答案 0 :(得分:1)
使用http状态代码404的自定义错误页面,并始终重定向到您的控制器操作。 ASP.NET MVC 404 Error Handling
答案 1 :(得分:1)
在web.config中添加自定义错误页面网址
<customErrors mode="On" defaultRedirect="~/Home/Index" />
答案 2 :(得分:0)
将此添加到配置:
<customErrors mode="On">
<error statusCode="404" redirect="~/Home/Index"/>
</customErrors>
或其他方式:使用attrubute处理错误。创建属性:
public class HandleMyError : HandleErrorAttribute
{
public override void OnException( ExceptionContext filterContext )
{
if ( filterContext.ExceptionHandled ) { return ; }
else
{
string actionName = filterContext.RouteData.Values["action"].ToString();
Type controllerType = filterContext.Controller.GetType();
var method = controllerType.GetMethod( actionName );
var returnType = method.ReturnType;
if ( returnType.Equals( typeof( ActionResult ) ) || ( returnType ).IsSubclassOf( typeof( ActionResult ) ) )
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "area", "" }, { "controller", "Home" }, { "action", "Index" } });
}
}
filterContext.ExceptionHandled = true;
}
}
并为您的[HandleMyError]
控制器添加Home
属性:
[HandleMyError]
public class HomeController : BaseController
{
}