简体   繁体   中英

ASP.NET MVC request intercept and get model value

I have lots of controllers, which return data, based on parameters.

But users can fake the parameters they send to server, so I would like to intercept all requests, and if some parameter that come back with model is not valid, give warning/error.

the example header of controller is this

[Intercept<CarModel>] <-- I want something like this, <CarModel> because the interceptor knows what type to cast the model when intercepted
public object Cards(CarModel model) {

I would like to create this kind of attribute, that intercepts the controller, checks if model is valid.

How could I do this? I googled about it, but not found anything like this.

Just put your validation code in the action. Better yet, inherit from an IValidatable interface and implement HasPropertiesValid() on all your models. Then you just call model.HasPropertiesValid(); at the beginning of your action.

Validatable interface

interface IValidatable {
    bool IsPropertiesValid();
}

A model example

public class CarModel : IValidatable {
    public string ModelName {get;set;}
    public string ManufacturerName {get;set;}
    public bool IsPropertiesValid() {
        if(ManufacturerName == "Toyota") { 
            if(ModelName == "Prius") return true;
        }
        return false;
    }
}

Controller

public ActionResult ToyotaCar(CarModel model){
    if(!model.IsPropertiesValid()) return RedirectToAction("QuitMessingAround","CaughtYou");
}

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