Boh*_*dan 1 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4
让我们想象一下,我有以下行动
public ViewResult Products(string color)
{...}
Run Code Online (Sandbox Code Playgroud)
和url"products"映射到此操作的路由.
根据SEO提示链接/products?color=red应该返回
200好的
但链接 /products?someOtherParametr=someValue
404未找到
所以问题是 - 如何处理未出现的查询参数并在这种情况下返回404
考虑接受的答案是什么是从ASP.NET MVC操作发送HTTP 404响应的正确方法?,有一个特殊的ActionResult,可以满足您的期望.
public class HomeController : Controller
{
public ViewResult Products(string color)
{
if (color != "something") // it can be replaced with any guarded clause(s)
return new HttpNotFoundResult("The color does not exist.");
...
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
public class HomeController : Controller
{
public ViewResult Products(string color)
{
if (Request.QueryString.Count != 1 ||
Request.QueryString.GetKey(0) != "color")
return new HttpNotFoundResult("the error message");
...
}
}
Run Code Online (Sandbox Code Playgroud)
在执行Action Method之前验证这一点.此方法适用于您项目的所有Controller或特定的Action方法.
控制器动作方法
[attr] // Before executing any Action Method, Action Filter will execute to
//check for Valid Query Strings.
public class ActionResultTypesController : Controller
{
[HttpGet]
public ActionResult Index(int Param = 0)
{
return View();
}
[HttpPost]
public ActionResult Index(MyViewModel obj)
{
return View(obj);
}
}
Run Code Online (Sandbox Code Playgroud)
动作过滤器
public class attr : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionParameters.Count == 0 &&
System.Web.HttpContext.Current.Request.QueryString.Count > 0)
{
//When no Action Parameter exists and Query String exists.
}
else
{
// Check the Query String Key name and compare it with the Action
// Parameter name
foreach (var item in System.Web.HttpContext
.Current
.Request.QueryString.Keys)
{
if (!filterContext.ActionParameters.Keys.Contains(item))
{
// When the Query String is not matching with the Action
// Parameter
}
}
}
base.OnActionExecuting(filterContext);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你注意上面的代码,我们正在检查Action参数,如下面的屏幕所示.

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{"action", "ActionName"},
{"controller", "ControllerName"},
{"area", "Area Name"},
{"Parameter Name","Parameter Value"}
});
Run Code Online (Sandbox Code Playgroud)
要么
我们可以这样做.下面提到的代码将写入OnActionExecuting方法覆盖
filterContext.Result = new HttpStatusCodeResult(404);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2654 次 |
| 最近记录: |