2017-05-29 33 views
1

我處於需要將單個對象與字符串一起返回的情況..我對web api非常陌生,無法找出如何解決返回多個參數..從web api控制器方法返回單個對象和字符串

下面

是我迄今爲止嘗試過的代碼..

public async Task<IHttpActionResult> PostAuthenticationData(long id, string password) 
    { 
     Consumer consumer = await db.Consumers.FindAsync(id); 

     if (consumer == null) 
     { 
      return NotFound(); 
     } 

     if(consumer.ConsumerPassword != password) 
     { 
      return BadRequest(); 
     } 

     ConsumerSessionTokenLog consumerSessionTokenLog = await db.ConsumerSessionTokenLogs.FindAsync(id); 

     if(consumerSessionTokenLog == null) 
     { 
      return NotFound(); 
     } 
     else 
     { 
      string sessionToken = consumerSessionTokenLog.SessionToken; 
     } 

    /// here i need to return "sessionToken" and "consumer" object 
     return Ok(consumer); 
    } 

可以在任何一個,請在此查詢幫助..

提前感謝

回答

3

創建它包裝都值一類,或者你可以返回,像這樣一個匿名類型:

return Ok(new { consumer, sessionToken }); 

請注意,你需要吊sessionToken你的if語句範圍。

+0

感謝搶劫的幫助:) –

2

過不去定義結構返回:

struct MyReturType 
{ 
    object obj; 
    string str; 

    public MyReturType(object o, string s) 
    { 
     obj = o; 
     str = s; 
    } 
} 

然後返回:

public async Task<IHttpActionResult> PostAuthenticationData(long id, string password) 
    { 
     Consumer consumer = await db.Consumers.FindAsync(id); 

     if (consumer == null) 
     { 
      return NotFound(); 
     } 

     if(consumer.ConsumerPassword != password) 
     { 
      return BadRequest(); 
     } 

     ConsumerSessionTokenLog consumerSessionTokenLog = await db.ConsumerSessionTokenLogs.FindAsync(id); 

     if(consumerSessionTokenLog == null) 
     { 
      return NotFound(); 
     } 
     else 
     { 
      string sessionToken = consumerSessionTokenLog.SessionToken; 
     } 

    /// here i need to return "sessionToken" and "consumer" object 
     return Ok(new MyReturType(consumer,sessionToken)); 
    } 
相關問題