c#[MVC] WebApi는 다양한 유형(그림/json 데이터/문자열)을 반환합니다.

1420 단어
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;
}

좋은 웹페이지 즐겨찾기