c# WebApi之介面返回型別詳解
WebApi相關文章:
Webapi的介面返回值主要有四種類型
- void無返回值
- IHttpActionResult
- HttpResponseMessage
自定義型別
void無返回值
大家都知道void宣告的是一個無返回值的方法,宣告一個api控制器方法,例如:
public class ValuesController : ApiController
{
[HttpGet]
public void Get()
{
int a = 1;
int b = 2;
int c = a + b;
//.....................
}
}
使用postman,測試介面:
可以看到,void宣告的介面,在請求成功的時候得不到返回值,而且會返回http的狀態碼為204,表示沒有返回值。
IHttpActionResult
IHttpActionResult是WebApi最常用的一種返回值型別,常用的方式有:Json(T content)、Ok()、 Ok(T content)、NotFound()、Content(HttpStatusCode statusCode, T value)、BadRequest()、Redirect(string location)等
Json(T content)
在WebApi的ApiController這個抽象類裡面,為我們封裝了Json(T content)這個方法,它的用法和MVC裡面的JsonResult基本類似。
[HttpGet]
public IHttpActionResult getJson()
{
var list = new List<userinfo>();
list.Add(new userinfo { Name="jeck",age=22 });
list.Add(new userinfo { Name = "poor", age = 23 });
return Json<List<userinfo>>(list);
}
private class userinfo{
public string Name { get; set; }
public int age { get; set; }
}
測試結果:
為什麼可以返回 Json(T content)呢,轉到Json(T content)的定義,發現它返回的是JsonResult物件
再轉到JsonResult的定義,發現它實現了IHttpActionResult介面
當然也可以使用dynamic來返回一個物件
[HttpGet]
public IHttpActionResult getJson()
{
return Json<dynamic>(new { AA = "a", BB = "b" });
}
Ok()、 Ok(T content)
如果返回Ok(),就表示不向客戶端返回任何資訊,只告訴客戶端請求成功。
[HttpGet]
public IHttpActionResult getJson()
{
return Ok();
}
Ok(T content)向客戶端返回一個成功的物件
[HttpGet]
public IHttpActionResult getJson1()
{
string result = "請求成功!";
return Ok(result);
}
NotFound()
NotFound()方法會返回一個404的錯誤到客戶端。
[HttpGet]
public IHttpActionResult getJson()
{
return NotFound();
}
Content(HttpStatusCode statusCode, T value)
向客戶端返回值和http狀態碼。
[HttpGet]
public IHttpActionResult getJson()
{
return Content<string>(HttpStatusCode.OK, "OK");
}
BadRequest()
向客戶端返回400的http錯誤。
[HttpGet]
public IHttpActionResult getJson2()
{
return BadRequest();
}
Redirect(string location)
將請求重定向到其他地方。
[HttpGet]
public IHttpActionResult getJson3()
{
return Redirect("http://localhost:7408/api/Values/getJson1");
}
[HttpGet]
public IHttpActionResult getJson1()
{
string result = "請求成功!";
return Ok(result);
}
HttpResponseMessage
HttpResponseMessage這個物件,表示向客戶端返回一個http響應的訊息物件(包含http狀態碼和需要返回客戶端的訊息)。這個物件也有它獨特的使用場景:需要向客戶端返回HttpResponse時就要用到這個物件。以匯出為例,由於需要將匯出的Excel檔案輸出到客戶端瀏覽器,Webapi的服務端需要向Web的客戶端輸出檔案流,這個時候一般的IHttpActionResult物件不方便解決這個問題,於是HttpReponseMessage派上了用場。
public HttpResponseMessage Export()
{
//取資料
var lstRes = OrderBLL.Export();
//向Excel裡面填充資料
HSSFWorkbook workbook = new HSSFWorkbook();
CreateAndFillSheet(workbook, lstRes);
//儲存到服務
var fileName = "Excel" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
var strPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data\" + fileName);
using (FileStream fs = new FileStream(strPath, FileMode.Create))
{
workbook.Write(fs);
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
}
}
//輸出到瀏覽器
try
{
var stream = new FileStream(strPath, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
return response;
}
catch
{
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
自定義型別
你也可以將webapi的介面和普通方法一樣,返回任意的型別,WebApi會自動序列化你自定義任何返回型別,然後將序列化的值寫到響應正文裡,狀態碼統一返回200。
[HttpGet]
public object getJson()
{
var list = new List<userinfo>();
list.Add(new userinfo { Name = "work", age = 11 });
list.Add(new userinfo { Name = "hard", age = 12 });
return list;
}