我想做以下事情:
当网址没有instID时,我想重定向到“Instelling”
操作
在这个 Controller 中,每个方法都需要instID。
[RequiredParameter(parameterName="instID", controllerToSend="Instelling")]
public ActionResult Index(int? instID) {
//if (!instID.HasValue) {
// return RedirectToAction("Index", "Instelling");
//}
var facts = _db.Instellingens.First(q => q.Inst_ID == instID).FacturatieGegevens;
return View(facts);
}
所以这是在 Controller 中。
Action 过滤器:
namespace MVC2_NASTEST.Controllers {
public class RequiredParameterAttribute : ActionFilterAttribute {
public string parameterName { get; set; }
public string actionToSend { get; set; }
public string controllerToSend { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (parameterName != string.Empty) {
if (filterContext.ActionParameters.ContainsKey(parameterName) && filterContext.ActionParameters[parameterName] != null) {
string s = "test";
//all is good
} else {
//de parameter ontbreekt. kijk of de controller en de action geset zijn.
if (actionToSend == string.Empty)
actionToSend = "Index";
if (controllerToSend == string.Empty) {
controllerToSend = filterContext.Controller.ToString();
controllerToSend = controllerToSend.Substring(controllerToSend.LastIndexOf(".") + 1);
controllerToSend = controllerToSend.Substring(0, controllerToSend.LastIndexOf("Controller"));
}
UrlHelper helper = new UrlHelper(filterContext.RequestContext);
string url = helper.Action(actionToSend, controllerToSend);
HttpContext.Current.Response.Redirect(url);
//filterContext.HttpContext.Response.Redirect(url, true);
}
}
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
base.OnActionExecuted(filterContext);
}
}
}
事情是:它确实有效,但是,操作本身首先被执行,然后重定向发生。这不是我想要的。
也许我不应该使用actionfilters而只是添加一条路线? 在这种情况下,如果 instID 丢失,我如何将路由重定向到另一个 Controller ?
最佳答案
您可以考虑更改为授权过滤器,而不是创建操作过滤器(在操作方法返回之前运行),它允许您重定向到替代 Controller 和操作
类似这样的东西(伪代码):
public class RequiredParameterAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// read instID from QueryString
// if instId is null, return false, otherwise true
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.result = new RedirectToRouteResult( new { controller = "MyController" , action = "MyAction" } )
}
}
关于asp.net-mvc - MVC 使用 Action Filter 检查 URL 中的参数。停止执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3883466/