简体   繁体   中英

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:

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 . 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?

Many times our clients write things like 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. So for Google our page is wrong.

If you want to enable this scenario, you should declare the FixedWidthHeight parameter to be a string, and parse it to a boolean yourself.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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