Web API可选参数 [英] Web API optional parameters

查看:117
本文介绍了Web API可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下签名的控制器:

I have a controller with the following signature:

[Route("products/filter/{apc=apc}/{xpc=xpc}/{sku=sku}")]
public IHttpActionResult Get(string apc, string xpc, int? sku)
{ ... }

我用以下URI调用此方法:

I call this method with following URIs:

  • 〜/api/products/filter?apc = AA& xpc = BB
  • 〜/api/products/filter?sku = 7199123

第一个URI正常工作.第二个有一个奇怪的副作用.即使未提供apc和xpc的默认值应为null,但这些参数实际上是它们的名称.我可以通过添加其他逻辑来克服这一点:

The first URI works without issue. The second one has a strange side effect. Even though the default values for apc and xpc should be null when not provided, the parameters are actually their names. I can overcome this by adding the additional logic:

apc = (apc == "apc") ? null : apc;
xpc = (xpc == "xpc") ? null : xpc;

这看起来像是黑客,如果传递的值等于参数名,那将是有问题的.

This seems like a hack, and would be problematic if value passed was ever equal to the parameter name.

是否有没有这种副作用的路线定义方法?

Is there a way to define the Route without this side effect?

推荐答案

我知道了.我使用的是一个错误的示例,该示例在过去发现了如何将查询字符串映射到方法参数.

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

万一其他人需要它,以便在查询字符串中具有可选参数,例如:

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • 〜/api/products/filter?apc = AA& xpc = BB
  • 〜/api/products/filter?sku = 7199123

您将使用:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

当这些类型已经具有默认值时,必须为方法参数定义默认值似乎很奇怪.

It seems odd to have to define default values for the method parameters when these types already have a default.

这篇关于Web API可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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