目前在我的 rewriterules.config 中,我设置了以下规则:
<rule name="PublicUrl" stopProcessing="true">
<match url="^public-url.html$" />
<action type="Rewrite" url="public-url.html?query=string" />
</rule>
我使用的是 MVC 版本 4,想知道是否有办法在 RouteConfig.cs 中添加查询字符串(向后兼容需要),而不是在 rewriterules.config 中添加。
Controller 中的操作结果如下所示:
public ActionResult Test(string strParam)
{
return View("BuildingListingPage");
}
RouteConfig.cs 中的路由是这样的:
routes.MapRoute(
name: "Publicurl",
url: " public-url.html ",
defaults: new { controller = "Home", action = "Test", strParam = "hi there”, querystring = "addme" }
);
我在这里的尝试是将默认值中的查询字符串附加到查询字符串变量。如果我要从 View 中使用 actionlink 或 URLHelper,我相信不匹配的参数确实会附加到查询字符串中。
我还尝试创建一个自定义类来实现 RouteBase 并将值添加到 RouteValue,但这并没有实现我的目标。
这里的问题是是否有办法从 Routeconfig.cs 中将变量附加到查询字符串变量。
最佳答案
这取决于您配置的目的。如果您只想在应用程序中使用查询字符串生成链接,则可以在生成链接时添加查询字符串。
假设以下路由配置:
routes.MapRoute(
name: "Publicurl",
url: "public-url.html",
defaults: new { controller = "Home", action = "Test" }
);
您可以使用如下查询字符串为此路线生成链接:
@Html.RouteLink("My Link", "Publicurl", new { strParam = "hi there", querystring = "addme" })
如果您只关心从用于处理此请求的 Controller 中获取的值,您可以将它们添加到 Controller 的 Action 方法中,它们将自动绑定(bind)。确保它们的名称与您在查询字符串中输入的名称相同:
public class TestController : Controller
{
// strParam and querystring will bound automatically, rename as appropriate
public ActionResult Index(string strParam, string querystring)
{
// Do something with the values
return View();
}
}
关于c# - mvc 添加查询字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476855/