Asp.net ASP MVC:如何在查询参数名称中使用连字符的路由?
我需要实现哪些组件,如何将其挂接到框架中,以便在URL中包含名称包含2个或多个用连字符分隔的单词的查询参数Asp.net ASP MVC:如何在查询参数名称中使用连字符的路由?,asp.net,asp.net-mvc,routing,asp.net-mvc-5,Asp.net,Asp.net Mvc,Routing,Asp.net Mvc 5,我需要实现哪些组件,如何将其挂接到框架中,以便在URL中包含名称包含2个或多个用连字符分隔的单词的查询参数 例如: 我会有这个网址: www.mysite.com/resource/i-am-looking-for?parameterOne=foo¶meterTwo=bar 我希望它是这样的: ActionResult DoSomething(string parameterOne, string parameterTwo) www.mysite.com/resource/i-am-
例如: 我会有这个网址: www.mysite.com/resource/i-am-looking-for?parameterOne=foo¶meterTwo=bar 我希望它是这样的:
ActionResult DoSomething(string parameterOne, string parameterTwo)
www.mysite.com/resource/i-am-looking-for?参数一=foo和参数二=bar
我的行动是这样的:
ActionResult DoSomething(string parameterOne, string parameterTwo)
原因是:用户友好的URL和一致性
我需要:
- 与框架URL帮助程序(URL.Action、URL.RouteUrl等)无缝集成的组件
- 要绑定到动作参数(或模型)的传入数据
谢谢大家! 客户端的url编码如何
通过这种方式,您可以使用常规方式调用控制器。请看一下其中一个答案:例如:这是你的行动
public ActionResult GetNew(int id)
{
return View(news.Where(i => i.Id == id).SingleOrDefault());
}
第一步
在项目中打开App_Start>RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "GetNew",
url: "news/new-detail/{id}",
defaults: new { controller = "News", action = "GetNew", id = ""}
);
}
}
现在运行您的项目并编写浏览器:…(与您不同)/news/new detail/1
新的1号身份证将打开。
我希望这会有所帮助
公共操作结果SomeAction(string Some Var){}
无效,因为在C#中,变量名不能包含连字符。但是,允许使用下划线,因此这是有效的public ActionResult SomeAction(string Some_Var){}
现在,如果您不再需要将强类型输入变量绑定到操作,您可以通过
Request.QueryString[“some var”]
实现您的目标,但您必须处理与之相关的类型转换和错误处理。您可以添加自定义值提供程序工厂,如下所示
public class MyQueryStringValueProvider : NameValuePairsValueProvider
{
public QueryStringValueProvider(
HttpActionContext actionContext,
CultureInfo culture)
: base(
() =>{
var request = actionContext.ControllerContext;
foreach(var pair in request
.GetQueryNameValuePairs()){
yield return new KeyValuePair<String,String)(
Transform(pair.Key), pair.Value
);
}, culture)
{
}
private String Transform(String key){
// just removing all - , as it is case insensitive
//
return key.Replace("-","");
}
}
ValueProviderFactories.Factories.Add(
new MyQueryStringValueProvider());
为了安全起见,您可以删除现有的QueryStringValueProvider,以避免没有破折号的键的名称冲突
对于Action Name中的破折号,您可以参考,我的问题不是关于编码,而是关于如何更改路由系统以更改url模式。@user2704您可以提供完整的请求url以更好地了解您需要的内容(url的一般部分和粗体的虚线参数)吗?@user2704,你需要用这些例子来编辑你的问题,这样你就能清楚地知道你想要达到什么目的。不清楚为什么要这样做,但可以使用自定义模型活页夹。@StephenMuecke ok;这是为了输入数据,但是关于url生成(我在列表中的第一点)呢?谢谢你的帮助,但是你不明白我想要什么。我可以有一个带有连字符的路由,但我希望查询参数名称也带有连字符。根据您的示例,我可以使用/news/new detail/1?parameterOne=2(即使“parameterOne”未绑定)