簡體   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