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

查看:33
本文介绍了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.

我实际上已经通过使用下面的方法找到了解决我的问题的方法/修复方法,它从 url 中删除了 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天全站免登陆