在asp.net web api中動態修改action的名字

來源:互聯網
上載者:User

在路由設定中,我的路由是這樣的:

/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, IControllerConfiguration2 {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 }

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.