简体   繁体   English

在Route属性ASP.NET MVC的URL中添加自定义单词

[英]Add custom word in the URL of Route attribute ASP.NET MVC

How to add a custom, user defined word in the URL of some MVC call? 如何在某些MVC调用的URL中添加自定义,用户定义的单词?

For example I have this attribute on my controller's method: 例如,我在控制器的方法上具有此属性:

[Route("accounts/transactions"]

What I'm trying to do is to change that route into this form: /accounts/{accountNumber}/transactions 我正在尝试将路由更改为以下形式: /accounts/{accountNumber}/transactions

Where accountNumber is changeable and send by client in the moment when request is send. 其中accountNumber是可更改的,并在发送请求时由客户端发送。 Client send his account number via URL like this: localhost:50490/accounts/1234567890/transactions and controller method gets invoked. 客户端通过这样的URL发送其帐号: localhost:50490/accounts/1234567890/transactions和控制器方法被调用。

Can I change Route parameter somehow so it can handle this situation or I need completely different solution. 我可以以某种方式更改Route参数,以便它可以处理这种情况,或者我需要完全不同的解决方案。

Yes you can change the route to handle this situation. 是的,您可以更改路线来处理这种情况。

Solution 1: 解决方案1:

 [Route("accounts/{accountNumber:int}/transactions"]
 public ActionResult Transactions(int accountNumber) {
     /* action body */
 }

Notes: 笔记:

1) accountNumber:int is just for integer and don't allow null. 1) accountNumber:int仅用于整数,不允许为null。

2) Your action must have accountNumber as parameter. 2)您的操作必须具有accountNumber作为参数。


Solution 2: You can add this route in RouteConfig 解决方案2:您可以在RouteConfig添加此路由

 routes.MapRoute(
      name: "accountNumber",
      url: "accounts/{accountNumber}/transactions",
      defaults: new { controller = "Accounts", action = "Transactions" }
 );

Your Action must take that as a parameter 您的操作必须将此作为参数

 public ActionResult Transactions(string accountNumber) {
     /* action body */
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM