MVC路由参数优先级 [英] MVC Routing Parameter Precedence

查看:152
本文介绍了MVC路由参数优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个默认的MVC路由设置的情况.像这样.

I came across a scenario where I had the default MVC Route setup. Like So.

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

然后像这样导航到网址

domain/controller/action/1234

然后在此页面上,我导航到同一页面,但在发生某个事件后使用不同的参数.像这样.

On this page I was then navigating to the same page but with different parameters after a certain event. Like so.

    var id = $(this).data("id");
    var url = "@Url.Action("action", "controller", new { area = ""})";
    var params = $.param({id: id, vrnsearch: true});
    var fullUrl = url += "?" + params;

    window.location.href = fullUrl;

我注意到url仍然在url中保留了相同的ID,并像这样附加了参数.

I noticed that the url was still keeping the same id in the url and attaching parameters like so.

domain/controller/action/1234?id=4321&vrnsearch=true

现在我的问题是,是否有一种方法可以确定是否应该使用url或参数中id的值的优先级.

Now my question is, is there a way to determine a precedence over if it should use the value for id from the url or from the parameter.

通过使用以下代码,我实际上找到了解决问题的方法/修复了该问题,该方法从网址中删除了ID,仅使用了参数.

I have actually found a work around/fix for my issue by using the below, which removes the id from the url and just uses parameters.

@Url.Action("action","controller", new {id = "", area = ""})

但是,我只是好奇参数与url路由是否优先.

However was just curious if there is a precedence in parameters vs url routing.

推荐答案

查询字符串与路由完全无关(至少,除非您自定义路由以考虑路由,否则无关).

The query string has nothing at all to do with routing (at least, not unless you customize routing to consider it).

传递给ModelBinder和您的操作方法的值由值提供者完成.您可以通过更改其相应的ValueProviderFactory在静态ValueProviderFactories.Factories属性中的注册顺序来控制优先顺序.

The values that are passed to the ModelBinder and to your action method are done so by Value Providers. You can control the order of precedence by changing the order in which their corresponding ValueProviderFactory is registered in the static ValueProviderFactories.Factories property.

如您所见,默认配置是首先使用RouteDataValueProviderFactory,如果它不返回任何值,则将尝试QueryStringValueProviderFactory.如果更改工厂的顺序,则优先顺序也会更改.

As you can see, the default configuration is to first use the RouteDataValueProviderFactory and if it returns no value it will try the QueryStringValueProviderFactory. If you change the order of the factories, the order of precedence changes.

ValueProviderFactories.Factories.RemoveAt(3);
ValueProviderFactories.Factories.Insert(4, new RouteDataValueProviderFactory());

这篇关于MVC路由参数优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆