Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c# - What is the purpose of FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters) inside Global.asax


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The FilterConfig is a custom class in your code, normally under the App_Start folder and generally looks somewhat like this:

public class FilterConfig {
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
        filters.Add(new HandleErrorAttribute());
    }
}

You can add custom filters to this list that should be executed on each request. If you inherit from the FilterAttribute class or one of its inheritors you can create your own filters, for instance a log filter.

You can also apply these filters to controllers that requires certain constraints. For instance, if you add the [RequireHttps] filter attribute (example below) to a controller or a method in your controller, the user must use a https request in order to execute the code in the method. So instead of handling it in each method, the filter takes care of it.

[RequireHttps]
public class MyController : ApiController {
    // only https requests will get through to this method.
    [HttpGet]
    public IHttpActionResult Get() {
       return Ok();
    }
}

You can think of it as a little box that sits between the users browser and your controller and filters out any invalid requests, or one the executes when a controller is done and you need to postprocess the result to the user.

If you want to read more, msdn has more details regarding filters at Filtering in ASP.NET MVC.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...