zoukankan      html  css  js  c++  java
  • webapi返回不同格式的数据

         //默认返回 json GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    
              //  GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));  
    
                //返回格式选择 datatype 可以替换为任何参数 //GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(              //    new QueryStringMapping("datatype", "xml", "application/xml")); 
    
    using System.IO;  
    /// <summary>  
    /// WebApi返回图片  
    /// </summary>  
    public HttpResponseMessage GetQrCode()  
    {  
        var imgPath = @"D:ITdosComImagesitdos.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;  
    }  

    //list 转成json格式

    string JsonString = string.Empty;
    JsonString = JsonConvert.SerializeObject(lstRes);

     
  • 相关阅读:
    递归实现全排列问题
    LeetCode
    LeetCode
    连续子元素最大和
    简单模板view调用
    如何清除PHP中不需要的Layout模板
    Model中设置表单验证方法
    数据修改操作
    MVC模式tp框架四中路由形式
    zend Framework的MVC模式的搭建
  • 原文地址:https://www.cnblogs.com/lyq666666/p/14948322.html
Copyright © 2011-2022 走看看