【问题标题】:How to validate the value of a parameter in the routes in ASP.NET MVC如何在 ASP.NET MVC 中验证路由中的参数值
【发布时间】:2018-12-10 20:23:55
【问题描述】:

我正在使用 C# 在 ASP.NET MVC 中进行开发,并且我有一个这样声明的操作:

public FileResult ViewImage (int ImageFileItemId, 
                             int MaxWidth, 
                             int MaxHeight, 
                             bool FixedWidthHeight, 
                             string JpegQuality)

我想验证参数FixedWidthHeight 客观上是truefalse。如果不是,我将找不到该操作并且不会出现错误,例如“错误参数值”。

我听说使用'constrains' 参数可以验证这一点,但是如何验证呢?

很多时候我们的客户会写https://.../ViewImage?ImageFileItemId= 6654&MaxWidth=800&MaxHeight=400&FixedWidthHeight=Trutes 之类的东西。通常,该操作会返回一个图像,在这种情况下它会给出错误。这个想法是发送 404,因为 Google 和其他网站将 URL 识别为有效。所以对于 Google,我们的页面是错误的。

【问题讨论】:

  • 很多时候我们的客户会写“https://.../ViewImage?ImageFileItemId= 6654&MaxWidth=800&MaxHeight=400&FixedWidthHeight=Trutes”之类的东西,该操作返回一个图像,它给出了一个错误,但这个想法是发送 404,因为 google 和其他他们认为 url 是有效的,而对于 google,我们的页面是错误的。
  • 我会使用 403 而不是 404。表明请求已被理解,但您不想完成它,原因在响应正文中进行了说明。

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4


【解决方案1】:

如果要启用此场景,应将FixedWidthHeight 参数声明为字符串,并自行解析为布尔值。

在伪代码中:

public FileResult ViewImage (int ImageFileItemId, 
                             int MaxWidth, 
                             int MaxHeight, 
                             string FixedWidthHeight, 
                             string JpegQuality)
{
    bool fixed;

    if (Boolean.TryParse(FixedWidthHeight, out fixed))
    {
        // Process the request normally
        // Where the 'fixed' variable holds the parsed value
    }
    else
    {
       // Return a 404, 403, 'parameter error' or something else
    }
}

【讨论】:

  • 非常感谢您的回答,我也尝试这样做,但我的老板觉得有更好的解决方案,因为其他操作也有同样的问题,他不想通过一切都串起来,如果您有任何其他想法,欢迎您,问候
  • "[Route("Site/ViewImage/{FixedWidthHeight:bool}")]" sabes como hacer algo como esto?
猜你喜欢
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2010-12-09
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多