简体   繁体   English

如何在Web API中传递可选参数

[英]How to pass optional parameters in Web API

Can you please help me to pass optional parameters in between in a uri 您能帮我在uri之间传递可选参数吗

[Route("api/values/{a}/{b?}/{c?}")]
public string Get(string a = "", string b = "", string c = "")
{
    return string.Format("a={0}, b={1}, c={2}", a, b, c);
}

I can call the api - 我可以调用api-

api/values/abc/pqr/xyz returns a=abc, b=pqr, c=xyz
api/values/abc/pqr returns a=abc, b=pqr, c=

But i would like to call the api like - 但是我想这样称呼api-

api/values/abc//xyz which should return a=abc, b=, c=xyz
returns a=abc, b=xyz, c=

Can anyone help 谁能帮忙

That's the way URI's are meant to be - they should represent certain path to the object. 这就是URI的含义-它们应该代表对象的某些路径。 You should not be able to get to "c" without specifying "b" or "a" on the way. 在途中未指定“ b”或“ a”的情况下,您应该无法进入“ c”。

But if you really want to, maybe just use some kind of wildcard as value? 但是,如果您真的想要,也许只是使用某种通配符作为值? For example: /api/values/abc/*/xyz and in your code just check if part of path is your wildcard. 例如:/ api / values / abc / * / xyz,然后在代码中检查路径的一部分是否为通配符。 That way you'll expand logic of URI's rather then breaking it. 这样,您将扩展URI的逻辑而不是破坏它。 URI will remain human-readable and obvious (eg. get all values XYZ that are somewhat descendant of container ABC). URI将保持人类可读性和明显性(例如,获取容器ABC的所有后代的所有值XYZ)。

To keep things DRY write a custom model binder that will convert any wildcard found in URL to a null (or other) value that will then be passed to your controller. 为了使事情保持干燥,请编写一个自定义模型绑定程序,该绑定程序会将URL中找到的所有通配符转换为null(或其他)值,然后将其传递给控制器​​。 Take a look at System.Web.Http.ModelBinding namespace to get you started. 看一下System.Web.Http.ModelBinding命名空间以开始。

A simple workaround would be to just use optional query parameters: 一个简单的解决方法是只使用可选的查询参数:

    [Route("api/values")]
    public string Get(string a = "", string b = "", string c = "")
    {
        return string.Format("a={0}, b={1}, c={2}", a, b, c);
    }

=> =>

/api/values?a=abc&c=xyz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM