开发者

ASP.NET MVC Controller parameter processing

开发者 https://www.devze.com 2022-12-25 06:46 出处:网络
In my application I have a string parameter called \"shop\" that is required in all controllers, but it needs to be transformed using code like this:

In my application I have a string parameter called "shop" that is required in all controllers, but it needs to be transformed using code like this:

        shop = shop.Replace("-", " ").ToLower();

How can I do this globally for all controllers without repeating this line in over and over? Thanks开发者_开发问答, Leo


Write a custom action filter, override OnActionExecuting() and apply the filter to all your controllers. (Or simply overriding OnActionExecuting() in your base controller, if you have a base controller at all.) The action method would look something like this:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var parameters = filterContext.ActionParameters;
    object shop;
    if (parameters.TryGetValue("shop", out shop))
    {
        parameters["shop"] = ((string)shop).Replace("-", " ").ToLower();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号