参考资料:C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
namespace WebApi.Controllers
{
public class HomeController : ApiController
{
[HttpGet]
public int GetByAge(string name)
{
if (name == "admin") return 25;
if (name == "lily") return 18;
return 0; //Action 的返回值可以是普通类型,这是最常用的。
}
[HttpGet]
public void ExecuteFun()
{
//Action 的返回值可以为void,这样客户端会得到204 的状态码,尽量别这样干
}
public IHttpActionResult Add(int i)
{
if (i == 1)
{
return Ok(); //如果返回Ok(),就表示不向客户端返回任何信息,只告诉客户端请求成功。
}
if (i == 2)
{
return Json(new { code = 0, data = "abc" }); //返回一个json数据
}
if (i == 3)
{
List<string> list = new List<string>() { "tom", "lily", "luc" }; //返回一个泛型json数据
return Json<List<string>>(list);
}
if (i == 4)
{
return Content(HttpStatusCode.OK, new { data = "abc" }); //向客户端返回http状态码和值(值可以是对象,也可以是其他类型)
}
if (i == 5)
{
return Content<string>(HttpStatusCode.OK, "abc");//向客户端返回http状态码和指定类型的值
}
if (i == 6)
{
return StatusCode(HttpStatusCode.NotFound); //返回一个状态码 HttpStatusCode是一个枚举
}
if (i == 7)
{
return BadRequest("错误"); //向客户端返回400的http错误。
}
return NotFound();//NotFound()方法会返回一个404的错误到客户端。
}
//向客户端返回一个http响应的消息对象(比较精细化的控制返回消息)
public HttpResponseMessage Index()
{
HttpResponseMessage msg = new HttpResponseMessage();
msg.StatusCode = System.Net.HttpStatusCode.OK; //设置http状态码
msg.Content = new StringContent("内容哈哈哈哈");
msg.Headers.Add("UserName", "Tom");
msg.Headers.Age = TimeSpan.FromDays(2);
return msg;
}
public HttpResponseMessage Export()//导出的Excel文件输出到客户端浏览器
{
//取数据
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
{
//将文件流保存在StreamContent对象里面,然后输出到浏览器。在浏览器端即可将Excel输出。
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);
}
}
}
}