繁体   English   中英

如何使我的API操作接受null复杂类型?

[英]How do I make my API action accept null complex types?

所以这很完美

//localhost:1234/api/task/getData?id=1&name=test&phone=123456

public object GetData(long id, [FromUri] User complexType)
{
    //complexType is binding correctly
    return runSomeCode(id, complexType ?? User.Current);
}

但这不是。 不知道如何指定一个空的复杂类型。

//localhost:1234/api/task/getData?id=1

public object GetData(long id, [FromUri] User complexType)
{
    //complexType is not null, but all class properties are
    return runSomeCode(id, complexType ?? User.Current);
}

我什至尝试了此操作,但是遇到了“发现多个符合要求的操作”的新问题

//localhost:1234/api/task/getData?id=1

public object GetData(long id)
{
    return runSomeCode(id, User.Current);
}

public object GetData(long id, [FromUri] User complexType)
{
    return runSomeCode(id, complexType);
}

这是我的复杂课堂的样子

public class User
{
    public string Name {get;set;}
    public string Phone {get;set;}

    public static User Current
    {
        get
        {
            //code to get the current user
        }
    }
}

更新我知道将方法更改为POST并使用正文内容是可行的,但是可以说我很固执,希望使用GET完成此操作。

如何在Web API GET请求中使复杂参数为空? 排除它不像POST请求那样工作。

我认为您正在寻找的是如何定义“路由规则”

WebApi 2.0让我们使用名为Route的属性来定义不同的“资源URL”,并使用一些规则(约束),例如长度,格式和默认值

例如:

public class SomeController : ApiController{
     //where author is a letter(a-Z) with a minimum of 5 character and 10 max.      
    [Route("html/{id}/{newAuthor:alpha:length(5,10)}/age:int?")]
    public Book Get(int id, string newAuthor , int age){
        return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
    }

其中参数ageinteger类型和optional类型。

或像这样使用默认值:

[Route("html/{id}/{newAuthor:alpha:length(5,10)}/age:int=33")]
public Book Get(int id, string newAuthor , int age){
  return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
    ...

或者能够根据您的需求自定义路由,例如:

[Route("url1/{id}")]
public Book Get(int id){
   return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian " };
}

[Route("url1/{id}/{author}")]
public Book Get(int id, string author){
   return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + author };
}
...

在WebApi的第一个版本中,必须在WebApiConfig类中完成此操作,但是选项并不相同,我认为该版本上唯一真正的选项是使用正则表达式。

回到Web.Api 20,您还可以通过继承IHttpRouteConstraint来定义自己的约束来处理自己的复杂类型。

在WEB.Api文档站点上有关于您描述的方案的其他信息,可能可能需要实现TypeConverter

http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

暂无
暂无

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

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