如何在ASP .NET MVC返回404页面时查询字符串参数是不正确 [英] How to return 404 page in ASP .NET MVC when query string parameters is incorrect

查看:133
本文介绍了如何在ASP .NET MVC返回404页面时查询字符串参数是不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象一下,我有以下作用

Let's imagine I have the following action

public ViewResult Products(string color)
{...}

和地图网址产品这一行动路线。

and route which maps url "products" to this action.

据搜索引擎优化技巧链接 /产品?的color = red 应返回

According to SEO tips link /products?color=red should return

200 OK

但链接 /产品?someOtherParametr = someValue中

404未找​​到

所以,问题是 - 如何处理unexisting查询参数和在这种情况下,返回404

So the question is - how to handle unexisting query parameters and return 404 in this case

推荐答案

执行操作方法之前验证这一点。这种方法适用于你的项目的所有控制器或特定的操作方法。
搜索结果

控制器操作方法

[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);
    }

}

行动过滤器

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);
    }
}

如果你留意上面的code,我们正在检查如下面的屏幕显示出的动作参数。

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
                        {
                            {"action", "ActionName"},
                            {"controller", "ControllerName"},
                            {"area", "Area Name"},
                            {"Parameter Name","Parameter Value"}
                        });

或者

我们可以这样做。以下提到的code将被写在 OnActionExecuting 方法重写

We can do like this. The below mentioned code will be written in the OnActionExecuting Method Override

filterContext.Result = new HttpStatusCodeResult(404);

这篇关于如何在ASP .NET MVC返回404页面时查询字符串参数是不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆