【问题标题】:Validate route values asp net mvc验证路由值 asp net mvc
【发布时间】:2016-12-02 10:01:14
【问题描述】:

我想在执行控制器操作之前验证 url。 用户使用如下所示的 url 运行应用程序:

https://appAddress/appAdress2/{first}/?secondId=ASD&thirdId=FGH&fourthId=123

"first" and "secondId" values are mandatory and they are string.
"thirdId" and "fourthId" are optional and "thirdId" is string and "fourthId" is int.

我可以这样做吗,例如使用 attibute 还是应该检查控制器操作中的值?

public ActionResult MyAction()
{
//todo: validation
}

我使用 ASP.NET MVC 5

【问题讨论】:

  • 你处理的是哪个 MVC 版本? MVC 5 具有属性路由约束规则,可以根据需要自定义任何 URL,即{action}/?id2=val2&id3=val3&id4=val4。确保您的操作方法也包含 4 个参数。
  • @TetsuyaYamamoto - 实际上,RouteAttribute 不适用于查询字符串值,所以这是不可能的。
  • 不清楚你在问什么。您想以什么方式“验证”参数?如果他们没有通过验证会发生什么? 404 没找到?还有什么?
  • @NightOwl888 如果错误,系统重定向到错误页面。
  • @TetsuyaYamamoto 我使用 MVC 5

标签: .net asp.net-mvc validation routes asp.net-mvc-routing


【解决方案1】:

验证请求具有所有必要信息的最简单方法是在您的操作方法中检查它。

public ActionResult MyAction(string first, string secondId, string thirdId, string fourthId)
{
    if (/* parameters are not valid */)
    {
        // Take invalid action...
        throw new ArgumentException("parameters are invalid");
    }
}

上面会抛出一个异常,(只要你的错误页面在web.config中配置)就会显示错误页面。一般而言,出于安全原因,您不应该告知用户发生了什么具体错误。

默认值提供者自动将参数从路由值和/或查询字符串值传递到请求中。您需要做的就是确保名称(可能还有数据类型)与您的路由/查询字符串中的名称匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2012-06-16
    • 1970-01-01
    相关资源
    最近更新 更多