在asp.net web api中动态修改action的名字

本文介绍了一种方法,在路由设置中通过添加自定义控制器配置属性,实现当URL包含特定字符串(如'jqGrid')时,执行预设的方法(如'jqGrid_List')。详细步骤包括创建控制器配置类、自定义控制器选择器,以及在请求处理阶段的逻辑调整。

在路由设置中,我的路由是这样的:

/api/{controller}/jqGrid/{action}/{id}

对于如下URL,默认情况下执行的是UserController类的List方法:

/api/User/jqGrid/List

而我希望凡是url中含有jqGrid的路由,都执行“jqGrid_{action}”名字的方法,即  jqGrid_List 方法。经过数天地折磨,终于解决了。上代码(这里照搬我在stackoverflow上的提问和我自己的回答了,英语高手欢迎指出文中不地道的英语,谢谢):

First of all, I need to add a JqGridControllerConfiguration attribute to replace the default action selector applied to the controller with my one.

[JqGridControllerConfiguration]
public class UserController : ApiController
{
    // GET: /api/User/jqGrid/List
    [HttpGet]
    public JqGridModel<User> jqGrid_List()
    {
        JqGridModel<User> result = new JqGridModel<User>();
        result.rows = Get();
        return result;
    }
}

Here's the code of JqGridControllerConfiguration:

1 public class JqGridControllerConfiguration : Attribute, IControllerConfiguration
2 {
3     public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
4     {
5         controllerSettings.Services.Replace(typeof(IHttpActionSelector), new JqGridActionSelector());
6     }
7 }

in JqGridActionSelector, the "action" is modified if a "jqGrid/" exists in the request URL.

 1 public class JqGridActionSelector : ApiControllerActionSelector
 2 {
 3     public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
 4     {
 5         Uri url = controllerContext.Request.RequestUri;
 6         if (url.Segments.Any(s => string.Compare(s, "jqGrid/", true) == 0))
 7         {
 8             controllerContext.RouteData.Values["action"] = "jqGrid_" + controllerContext.RouteData.Values["action"].ToString();
 9         }
10 
11         return base.SelectAction(controllerContext);
12     }
13 }

 

 

转载于:https://www.cnblogs.com/Ricky81317/archive/2012/09/10/2678717.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值