1. 程式人生 > >WebService返回文字JSON資料格式

WebService返回文字JSON資料格式

WebService返回的格式都是xml

Markup
<?xml version="1.0" encoding="utf-8"?><string xmlns="">Hello World</string>

 在前段js處理時需要先解析xml

JavaScript
$.parseXML(xmlstr).find("string").text();

處理起來費勁還有相容性問題 

現在網站都已經返回json格式了

Markup
<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">
{"Name":"張三","Age":18}</string>

 還是需要先處理xml在轉化json字串

讓WebService直接返回JSON資料格式方法一:

C#
    [WebMethod]

    public void HelloWorld()

    { 

        string str= "Hello World"; 

        Context.Response.Write(str);

        Context.Response.End();

    }

能直接得到字串格式,缺點就是每個方法都需要寫Context.Response.Write和Context.Response.End

讓WebService直接返回JSON資料格式方法二:

在Web.config中增加

C#
    <modules>

      <add name="AsmxRequestModule" type="AsmxRequestModule"/>

    </modules>

IIS經典模式 是httpModules

在appcode新增類檔案

C#
public class AsmxRequestModule : IHttpModule

{

    public void Init(HttpApplication context)

    {

        context.
BeginRequest += new EventHandler(Application_BeginRequest); } public void Dispose() { } public void Application_BeginRequest(object sender, EventArgs e) { HttpApplication application = sender as HttpApplication; string extension = Path.GetExtension(application.Request.Path); if (application.Request.Path.IndexOf("/WebService.asmx/") > -1) { application.Response.Filter = new CatchTextStream(application.Response.Filter); } } }
C#
public class CatchTextStream : Stream
{
    #region 資料流
    /// <summary>
    /// 資料流
    /// </summary>
    private Stream output;
    #endregion
    #region 建構函式
    /// <summary>
    /// 建構函式
    /// </summary>
    /// <param name="s"></param>
    /// <param name="requestInd"></param>
    /// <param name="logObj"></param>
    /// <param name="requestStr"></param>
    public CatchTextStream(Stream s)
    {
        output = s;
    }
    #endregion
    #region 過載屬性及方法
    public override bool CanRead
    {
        get { return output.CanRead; }
    }
    public override bool CanSeek
    {
        get { return output.CanSeek; }
    }
    public override bool CanWrite
    {
        get { return output.CanWrite; }
    }
    public override void Flush()
    {
        output.Flush();
    }
    public override long Length
    {
        get { return output.Length; }
    }
    public override long Position
    {
        get { return output.Position; }
        set { output.Position = value; }
    }
    public override int Read(byte[] buffer, int offset, int count)
    {
        return output.Read(buffer, offset, count);
    }
    public override long Seek(long offset, SeekOrigin origin)
    {
        return output.Seek(offset, origin);
    }
    public override void SetLength(long value)
    {
        output.SetLength(value);
    }
    public override void Write(byte[] buffer, int offset, int count)
    {
        if (HttpContext.Current != null)
        {
            HttpContext context = HttpContext.Current;
            Encoding encoding = context.Response.ContentEncoding;
            string responseInfo = encoding.GetString(buffer, offset, count);
            responseInfo = responseInfo.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<string xmlns=\"http://tempuri.org/\">", "");
            responseInfo = responseInfo.Substring(0, responseInfo.Length - 9);
            buffer = encoding.GetBytes(responseInfo);
            output.Write(buffer, 0, buffer.Length);
        }
    }
    #endregion
}

然後 在前臺呼叫,已經可以直接返回不帶xml的文字資料啦,這樣就可以直接在webservice呼叫方法裡面用Newtonsoft.Json.JsonConvert轉化成JSON格式返回了。

QQ截圖20170704122716.png

轉載自:http://www.qyuit.com/post/65.html