2012-05-30 59 views
8

我一直在尋找最近3個小時的100個鏈接,例如將scriptfactory添加到webconfig ,3個錯誤,設置內容類型等。Asmx web服務返回xml而不是json,試圖從服務輸出中刪除<string xmlns =「http://tempuri.org/」>

我無法弄清楚究竟是什麼錯誤。

環境:在.NET 4.0 Web應用程序運行在.NET 4.0

要求運行 服務: 我需要一個jqGrid的綁定與正在返回我JSON作爲字符串ASMX Web服務。 Web服務文件包含以下代碼。

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[ScriptService] 
public class SampleService : System.Web.Services.WebService 
{ 
    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string GetJsonServerProcess() 
    { 
     int memory = 1; 
     string json = string.Empty; 
     var obj = (System.Diagnostics.Process.GetProcesses().Where(r => r.WorkingSet64 > memory).Select(p => new { p.ProcessName, p.WorkingSet64 }).ToArray()); 
     json = Lib.ToJSON(obj); 
     return json; 
    } 
} 

JavaScript是如下

<script type="text/javascript"> 
    $(document).ready(function() { 
     jQuery("#jqgajax").jqGrid({ 
      ajaxGridOptions: { type: "POST", contentType: 'application/json; charset=utf-8' }, 
      url:'http://localhost:1092/SampleService.asmx/GetJsonServerProcess', 
      datatype: "json", 
      data: "{}", 
      colNames: ['ProcessName', 'WorkingSet64'], 
      colModel: [ 
         { name: 'ProcessName', index: 'ProcessName', width: 55 }, 
         { name: 'WorkingSet64', index: 'WorkingSet64', width: 90 } 
        ], 
      rowNum: 10, 
      width: 700, 
      rowList: [10, 20, 30], 
      sortname: 'invdate', 
      viewrecords: true, 
      sortorder: "desc", 
      caption: "New API Example" 
     }); 
    }); 
</script> 

HTML是Invoke按鈕,當點擊如下

<table id="jqgajax"> 
</table> 
<div id="jqgajax"> 
</div> 

Web服務輸出

<string xmlns="http://tempuri.org/"> 
[{"ProcessName":"Dropbox","WorkingSet64":22736896}, 
{"ProcessName":"fdhost","WorkingSet64":1941504}, 
{"ProcessName":"IntelliTrace","WorkingSet64":39276544} 
] 
</string> 

請提出我缺少的東西。 <string xmlns="http://tempuri.org/">標籤讓我很煩惱。我假設這些標籤不讓我的網格能夠綁定。

UPDATE:

ASMX服務現在看起來如下。

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[ScriptService] 
public class SampleService : System.Web.Services.WebService 
{ 
    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public List<demo> GetJsonServerProcess() 
    { 
     List<demo> test = new List<demo>(); 

     for(int i=1;i<=10;i++) 
      test.Add(new demo { ProcessName = string.Format("Sample {0}",i), WorkingSet64 = i }); 

     var re = test; 
     return re; 
    } 
} 

public class demo 
{ 
    public string ProcessName { get; set; } 
    public int WorkingSet64 { get; set; } 
} 
+0

可能的重複:http://stackoverflow.com/questions/11088294/asp-net-asmx-web-service-returning-xml-instead-of-json –

+0

問題是類似的,但解決方案是不同的。在鏈接解決方案中,修復程序是修改web.config文件,在此解決方案中,修復程序是修改Content-Type標頭。儘管如此,它們可能不是相互排斥的解 – akousmata

回答

6

點擊Invoke按鈕返回XML,因爲請求不指定contentType: 'application/json; charset=utf-8'。所以點擊Invoke按鈕的實驗並不是真的。

您代碼中的主要問題是您將數據轉換爲web方法內部的字符串。該行

json = Lib.ToJSON(obj); 

是不需要的。通常做的是返回對象。該GetJsonServerProcess應改爲類似

[ScriptService] 
public class SampleService : System.Web.Services.WebService 
{ 
    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public List<Process> GetJsonServerProcess() 
    { 
     int memory = 1; 
     return System.Diagnostics.Process.GetProcesses() 
        .Where(r => r.WorkingSet64 > memory) 
        .Select(p => new { p.ProcessName, p.WorkingSet64 }) 
        .ToList(); 
    } 
} 

接下來的問題是,默認的輸入格式等的jqGrid是另一個(見here)。所以你可以指定jsonReader來描述數據格式。在你的情況下,它會像

jsonReader: { 
    repeatitems: false, 
    id: "ProcessName", 
    root: function (obj) { return obj; }, 
    page: function() { return 1; }, 
    total: function() { return 1; }, 
    records: function (obj) { return obj.length; } 
} 

另外,你不應該使用http://localhost:1092/前綴阿賈克斯url因爲你只CAL從出於安全原因,同一個站點的數據。 jqGrid中的data參數與jQuery中的另一個含義相同,因此應刪除data: "{}"並將type: "POST"ajaxGridOptions移至mtype: "POST"。結果你會有類似的東西

$(document).ready(function() { 
    $("#jqgajax").jqGrid({ 
     mtype: "POST", 
     ajaxGridOptions: { contentType: 'application/json; charset=utf-8' }, 
     url: '/SampleService.asmx/GetJsonServerProcess', 
     postData: "{}", // remove all parameters which jqGrid send typically 
     datatype: "json", 
     colNames: ['ProcessName', 'WorkingSet64'], 
     colModel: [ 
      { name: 'ProcessName', index: 'ProcessName', width: 155 }, 
      { name: 'WorkingSet64', index: 'WorkingSet64', width: 190 } 
     ], 
     jsonReader: { 
      repeatitems: false, 
      id: "ProcessName", 
      root: function (obj) { return obj; }, 
      page: function() { return 1; }, 
      total: function() { return 1; }, 
      records: function (obj) { return obj.length; } 
     }, 
     rowNum: 10, 
     loadonce: true, 
     gridview: true, 
     height: 'auto', 
     rowList: [10, 20, 30], 
     viewrecords: true, 
     sortorder: "desc", 
     caption: "New API Example" 
    }); 
}); 

我沒有測試代碼,但它應該更接近你所需要的。

已更新:您應該通過更改jsonReader來修復代碼。您可以下載工作演示here。它顯示網格

enter image description here

我在服務器端的代碼

using System.Collections.Generic; 
using System.Diagnostics; 
using System.Linq; 
using System.Web.Services; 

namespace jqGridWebASMX 
{ 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    [System.Web.Script.Services.ScriptService] 
    public class SampleService : WebService 
    { 
     [WebMethod] 
     public List<Demo> GetJsonServerProcess() 
     { 
      const int memory = 1; 
      return Process.GetProcesses() 
       .Where (r => r.WorkingSet64 > memory) 
       .Select(p => new Demo { 
        Id = p.Id, 
        ProcessName = p.ProcessName, 
        WorkingSet64 = p.WorkingSet64 
       }) 
       .ToList(); 
     } 
    } 

    public class Demo 
    { 
     public int Id { get; set; } 
     public string ProcessName { get; set; } 
     public long WorkingSet64 { get; set; } 
    } 
} 

,並在客戶端

$("#list").jqGrid({ 
    mtype: "POST", 
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' }, 
    url: '/SampleService.asmx/GetJsonServerProcess', 
    postData: "{}", // remove all parameters which jqGrid send typically 
    datatype: "json", 
    colNames: ['ProcessName', 'WorkingSet64'], 
    colModel: [ 
     { name: 'ProcessName', index: 'ProcessName', width: 200 }, 
     { name: 'WorkingSet64', index: 'WorkingSet64', width: 120, 
      formatter: 'integer', sorttype: 'int', align: 'right' } 
    ], 
    jsonReader: { 
     repeatitems: false, 
     id: "Id", 
     root: function (obj) { return obj.d; }, 
     page: function() { return 1; }, 
     total: function() { return 1; }, 
     records: function (obj) { return obj.d.length; } 
    }, 
    rowNum: 10, 
    loadonce: true, 
    gridview: true, 
    height: 'auto', 
    pager: '#pager', 
    rowList: [10, 20, 30], 
    rownumbers: true, 
    viewrecords: true, 
    sortorder: "desc", 
    caption: "New API Example" 
}); 
$("#pager_left").hide(); // hide unused part of the pager to have more space 
+0

''你不應該在Ajax url中使用http:// localhost:1092 /前綴'當前我創建了兩個不同的解決方案,一個用於Web應用程序的另一個服務。截至目前,我還沒有在IIS上託管這項服務,並直接將此服務用於其他應用程序以進行測試。我試圖實現jqGrid。因此,在這種情況下,如果我使用服務的完整路徑,那會起作用嗎?在現場應用程序中,我會照顧網址。我會嘗試你所有的建議。但直到現在運行這一直都很困難。感謝您的支持。 –

+0

@ShantanuGupta:這只是Ajax的常見限制。該限制以[相同來源策略](http://en.wikipedia.org/wiki/Same_origin_policy)命名。因此,您無法訪問另一個主機或另一個端口作爲您發出請求的主機或端口*。像「http:// localhost:1092 /'這樣的前綴是沒有意義的。如果您應該只在同一個* web服務器上包含Web服務和相應的HTML/ASPX頁面。或者,您可以使用JSONP而不是JSON,但在實現用戶身份驗證更復雜的情況下,所以主要用於公共Web服務。 – Oleg

+0

我仍在努力解決數據問題。 Web服務不返回JSON。它在頂部添加XML標籤。 '' –

1

好的使用,我得到了同樣的錯誤,並經過嘗試和錯誤的負載這裏是我的「快速和骯髒」的解決方案;

$.get(url, {var1: parameter1, var2: parameter2}, function(data){ 
    data = JSON.parse($(data).find("string").text()); 
    alert("data.source: " + data.source); 
}); 
0
response = await client.GetAsync(RequestUrl, HttpCompletionOption.ResponseContentRead); 
       if (response.IsSuccessStatusCode) 
       { 
        _data = await response.Content.ReadAsStringAsync(); 
        try 
        { 
         XmlDocument _doc = new XmlDocument(); 
         _doc.LoadXml(_data); 
         return Request.CreateResponse(HttpStatusCode.OK, JObject.Parse(_doc.InnerText)); 
        } 
        catch (Exception jex) 
        { 
         return Request.CreateResponse(HttpStatusCode.BadRequest, jex.Message); 
        } 
       } 
       else 
        return Task.FromResult<HttpResponseMessage>(Request.CreateResponse(HttpStatusCode.NotFound)).Result; 
-1

對於有效的JSON響應使用此代碼..

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[ScriptService] 
public class SampleService : System.Web.Services.WebService 
{ 
    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public void GetJsonServerProcess() 
    { 
     int memory = 1; 
     string json = string.Empty; 
     var obj = (System.Diagnostics.Process.GetProcesses().Where(r => r.WorkingSet64 > memory).Select(p => new { p.ProcessName, p.WorkingSet64 }).ToArray()); 
     json = Lib.ToJSON(obj); 
     this.Context.Response.ContentType = "application/json; charset=utf-8"; 
      this.Context.Response.Write(json); 

    } 
} 
+0

請寫下你做了什麼,以及它對問題的有用程度。 –

-1

下面的代碼應該做的伎倆:

this.Context.Response.ContentType = "application/json; charset=utf-8"; 
this.Context.Response.Write(json); 
-1

此代碼工作完全

SqlDataAdapter sda = new SqlDataAdapter(strsql, ConfigurationManager.ConnectionStrings["BTConString"].ToString()); 
DataSet das = new DataSet(); 
sda.Fill(das); 
Context.Response.Output.Write(JsonConvert.SerializeObject(das, Newtonsoft.Json.Formatting.Indented)); 
Context.Response.End(); 

return string.Empty; 
+0

這對一個5歲的問題有一個可接受的答案有何貢獻? .... 不是很多... – VDWWD