如何在ASP.NET MVC中为属性路由添加默认参数 [英] how to add default parameters to attribute routes in asp.net mvc

查看:411
本文介绍了如何在ASP.NET MVC中为属性路由添加默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改基于约定的路由:

I am trying to change this convention based route:

routes.MapRoute(
    "MovieByReleaseDate",
    "movies/released/{year}/{month}",
    new { controller = "Movies", action = "ByReleasedDate" },
);

属性路由:

[Route("movies/released/{year}/{month}")]

但是我看不到如何像第一种方式那样定义默认参数。

but I can't see how I can define default parameters like in the first way.

推荐答案

多个[Route]属性以及可为空的参数,以实现您的目标。

You can use multiple [Route] attributes coupled with nullable parameters to achieve your goal.

[HttpGet]
[Route("movies/released/")]
[Route("movies/released/{year}")]
[Route("movies/released/{year}/{month}")]
public string Test(int? year = 2018, int? month = 1)
{
    return "The year is " + year;
}

当您向电影/不带年份的电影发送请求时,默认值用于一年。向电影/已发行/ 2000发送请求时,URL参数将覆盖默认值。

When you send a request to movies/released without a year, the default value is used for the year. When you send a request to movies/released/2000, the URL parameter overrides the default value.

这篇关于如何在ASP.NET MVC中为属性路由添加默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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