2015-07-21 49 views
1

我需要使用C#web服務來構建一個API,它需要以json格式返回值。從C#web服務中刪除xml頭文件

目前,我有下面的代碼行

namespace WebService1 
{ 
    /// <summary> 
    /// Summary description for Service1 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService] 
    public class Service1 : System.Web.Services.WebService 
    { 

     [WebMethod] 
     public string HelloWorld() 
     { 
      return new JavaScriptSerializer().Serialize(new { errMsg = "test" }); 
     } 
    } 
} 

這樣做的輸出,當POST方法被調用是

<?xml version="1.0" encoding="utf-8"?> 

<string xmlns="http://tempuri.org/">{"errMsg":"test"}</string> 

但是,這不是一個有效的JSON我怎麼做webservice只返回json對象而不是xml頭文件?

+0

你有沒有考慮過使用asp.net web api? –

回答

2

使用頭Content-Type:application/json調用此webservice會自動將響應轉換爲json,並且xml將消失。