加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC路由Maproute参数

发布时间:2020-12-15 19:48:42 所属栏目:asp.Net 来源:网络整理
导读:我正在进行MVC路由框架工作.我对RouteCollection.MapRoute方法所采用的参数感到有点困惑. 如果我采取了以下请求的传统示例 public class MvcApplication : System.Web.HttpApplication{ public static void RegisterRoutes(RouteCollection routes) { routes
我正在进行MVC路由框架工作.我对RouteCollection.MapRoute方法所采用的参数感到有点困惑.

如果我采取了以下请求的传统示例

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 - List item

        routes.MapRoute(
            "Default",// Route name
            "{controller}/{action}/{id}",// URL with parameters
            new { controller = "Home",action = "Index",id = "" }  // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

它使用以下签名进行映射

public static Route MapRoute(
    this RouteCollection routes,string name,string url,Object defaults
)

我的问题是关于“对象默认值”,

>为什么我们将它用作新的{controller =“Home”,action =“Index”,id =“”}
>这是固定格式吗?
> CLR如何解释参数序列?

跟进问题:

一个.为什么我们在一个括号{}内装饰控制器,动作或id?

湾URL指定和默认值之间是否有匹配?

解决方法

Why we are using it as new { controller = “Home”,action = “Index”,id = “” }

基本上用默认值初始化路由.传递给MapRoute方法的值转换为IDictionary< string,object>供以后查找.

Is this is a fixed format?

不,您可以根据您的网址省略或添加更多值.您在默认值中指定的值将用于查找.

例如,您可以设置路径名称Search,如下所示:

routes.MapRoute(
        name: "Search",url: "{controller}/{action}/{searchId}",defaults: new {controller = "Account",action = "Login",searchId = UrlParameter.Optional}
        );

How can CLR interprt sequenation of parameter?

通过将它们添加到Dictionary中(准确地说是RouteValueDictionary).

a. Why we decorate controller,action or id inside a bracket {}?

简短的回答,这是一个约定……根据MSDN的长答案,摘录自MSDN Article

In a URL pattern,you define placeholders by enclosing them in braces
( { and } ). You can define more than one placeholder in a segment,
but they must be separated by a literal value. For example,
{language}-{country}/{action} is a valid route pattern. However,
{language}{country}/{action} is not a valid pattern,because there is
no literal value or delimiter between the placeholders. Therefore,
routing cannot determine where to separate the value for the language
placeholder from the value for the country placeholder.

b. Is there any match in between URL specify and defaults?

是的,默认值是URL中的占位符.如果添加更多默认值然后添加占位符,则会忽略它.如果URL中未包含该参数的值,则使用默认值.

有关更多信息,我将向您指出这个优秀的MSDN Article.

希望这可以帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读