asp.net webapi:如何传递可选参数?

时间:2021-10-24 11:01:52

I am using the new asp.net web api and would like to pass optional parameters, i believe you need to populate an attribute so it allows me to pass params using the ? Symbol.

我正在使用新的asp.net web api,并希望传递可选参数,我相信你需要填充一个属性,所以它允许我使用传递params?符号。

Before this was done with with uri templates i believe.

在用uri模板完成之前我相信。

Does anyone have an example or any help really appreciated.

有没有人有一个例子或任何帮助真的很感激。

I am currently passing the id in the url which arrives in my controller as int I'd

我正在传递url中的id,它以int int的形式到达我的控制器

But I need to pass some dates

但我需要通过一些日期

2 个解决方案

#1


6  

You can make a parameter optional by using a nullable type:

您可以使用可空类型使参数可选:

public class OptionalParamsController : ApiController
{
    // GET /api/optionalparams?id=5&optionalDateTime=2012-05-31
    public string Get(int id, DateTime? optionalDateTime)
    {
        return optionalDateTime.HasValue ? optionalDateTime.Value.ToLongDateString() : "No dateTime provided";
    }
}

#2


3  

In addition to the previous answer provided by Ian, which is correct, you can also provide default values which I feel is a cleaner option which avoids having to check whether something was passed or not. Just another option.

除了Ian提供的前一个答案,这是正确的,您还可以提供默认值,我认为这是一个更清晰的选项,避免必须检查是否通过了某些事情。只是另一种选择。

public class OptionalParamsController : ApiController
{
    // GET /api/optionalparams?id=5&optionalDateTime=2012-05-31
    public string Get(int id, DateTime optionalDateTime = DateTime.UtcNow.Date)
    {...}
}

#1


6  

You can make a parameter optional by using a nullable type:

您可以使用可空类型使参数可选:

public class OptionalParamsController : ApiController
{
    // GET /api/optionalparams?id=5&optionalDateTime=2012-05-31
    public string Get(int id, DateTime? optionalDateTime)
    {
        return optionalDateTime.HasValue ? optionalDateTime.Value.ToLongDateString() : "No dateTime provided";
    }
}

#2


3  

In addition to the previous answer provided by Ian, which is correct, you can also provide default values which I feel is a cleaner option which avoids having to check whether something was passed or not. Just another option.

除了Ian提供的前一个答案,这是正确的,您还可以提供默认值,我认为这是一个更清晰的选项,避免必须检查是否通过了某些事情。只是另一种选择。

public class OptionalParamsController : ApiController
{
    // GET /api/optionalparams?id=5&optionalDateTime=2012-05-31
    public string Get(int id, DateTime optionalDateTime = DateTime.UtcNow.Date)
    {...}
}