且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC - 一个URL的参数提取

更新时间:2023-01-06 22:04:25

更新

RouteData.Values["id"] + Request.Url.Query

将匹配所有的例子

Will match all your examples

这是不完全清楚你想达到什么目的。 MVC模式,通过传递URL参数你绑定。

It is not entirely clear what you are trying to achieve. MVC passes URL parameters for you through model binding.

public class CustomerController : Controller {

  public ActionResult Edit(int id) {

    int customerId = id //the id in the URL

    return View();
  }

}


public class ProductController : Controller {

  public ActionResult Edit(int id, bool allowed) { 

    int productId = id; // the id in the URL
    bool isAllowed = allowed  // the ?allowed=true in the URL

    return View();
  }

}

添加一个路由映射到你的Global.asax.cs文件的默认之前将处理/管理/一部分。或者你可能想看看MVC领域。

Adding a route mapping to your global.asax.cs file before the default will handle the /administration/ part. Or you might want to look into MVC Areas.

routes.MapRoute(
  "Admin", // Route name
  "Administration/{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

如果这是你所追求的原始URL数据,那么你可以用在你的控制器动作提供的各种URL和请求属性之一

If it's the raw URL data you are after then you can use one of the various URL and Request properties available in your controller action

string url = Request.RawUrl;
string query= Request.Url.Query;
string isAllowed= Request.QueryString["allowed"];

这听起来像 Request.Url.PathAndQuery 可能是你想要的东西。

如果你想获得的原始发布的数据,你可以使用

If you want access to the raw posted data you can use

string isAllowed = Request.Params["allowed"];
string id = RouteData.Values["id"];