c# 【MVC】WebApi返回各种类型(图片/json数据/字符串)

2016/12/29 15:40
阅读数 5.2K
using System.IO;
/// <summary>
/// WebApi返回图片
/// </summary>
public HttpResponseMessage GetQrCode()
{
    var imgPath = @"D:\ITdosCom\Images\itdos.jpg";
    //从图片中读取byte
    var imgByte = File.ReadAllBytes(imgPath);
    //从图片中读取流
    var imgStream = new MemoryStream(File.ReadAllBytes(imgPath));
    var resp = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(imgByte)
        //或者
        //Content = new StreamContent(stream)
    };
    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
    return resp;
}
/// <summary>
/// WebApi返回json数据
/// </summary>
public HttpResponseMessage GetQrCode()
{
    var jsonStr = "{\"IsSuccess\":true,\"Data\":\"www.itdos.com\"}";
    var result = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(jsonStr, Encoding.UTF8, "text/json")
                    };
    return result;
}
/// <summary>
/// WebApi返回字符串
/// </summary>
public HttpResponseMessage GetQrCode()
{
    var str = "IT大师www.itdos.com";
    var result = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(str, Encoding.UTF8, "text/plain")
                    };
    return result;
}

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部