简体   繁体   English

如何在ASP.NET MVC中的路由中验证参数的值

[英]How to validate the value of a parameter in the routes in ASP.NET MVC

I am developing in ASP.NET MVC with C# and I have an action declared like this: 我正在使用C#在ASP.NET MVC中进行开发,并且有一个这样声明的动作:

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

I would like to validate that the parameter FixedWidthHeight is objectively true or false . 我想验证参数FixedWidthHeight客观上是true还是false If it is not, I will not find the action and there won't be an error, like 'error param value'. 如果不是,我将找不到操作,也不会出现错误,例如“错误参数值”。

I've heard that with the 'constrains' parameter you can validate that, but how? 我听说使用'constrains'参数可以验证这一点,但是如何?

Many times our clients write things like https://.../ViewImage?ImageFileItemId= 6654&MaxWidth=800&MaxHeight=400&FixedWidthHeight=Trutes . 很多时候,我们的客户编写类似https://.../ViewImage?ImageFileItemId= 6654&MaxWidth=800&MaxHeight=400&FixedWidthHeight=Trutes Normally the action returns an image, in this scenario it gives an error. 通常情况下,该操作会返回一个图像,在这种情况下,它将给出一个错误。 The idea is to send a 404, because Google and other websites recognize the URL as valid. 这个想法是发送404,因为Google和其他网站认为该URL有效。 So for Google our page is wrong. 因此,对于Google而言,我们的页面是错误的。

If you want to enable this scenario, you should declare the FixedWidthHeight parameter to be a string, and parse it to a boolean yourself. 如果要启用此方案,则应将FixedWidthHeight参数声明为字符串,然后自己将其解析为布尔值。

In pseudo code: 用伪代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM