Вопрос по jquery, json – Веб-служба Asmx, возвращающая xml вместо json, пытается удалить из вывода службы

8

Я искал 100 ссылок за последние 3 часа, например, добавление scriptfactory в webconfig, 3 ошибки, настройка типа контента и т. Д.

Я не могу понять, в чем на самом деле ошибка.

Среда: Служба работает на .net 4.0 Веб-приложение, работающее на .net 4.0

Требования: Мне нужно связать jqGrid с веб-сервисом asmx, который возвращает мне json в виде строки. Web service file contains following code.

[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 is as follows

<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 is as follows

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

Вывод веб-сервиса при нажатии на кнопку Invoke

<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 service now looks like as below.

[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; }
}
Error: User Rate Limit Exceeded akousmata
Error: User Rate Limit Exceededstackoverflow.com/questions/11088294/… mas_oz2k1

Ваш Ответ

6   ответов
6

Error: User Rate Limit ExceededcontentType: 'application/json; charset=utf-8'Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

json = Lib.ToJSON(obj);

Error: User Rate Limit ExceededGetJsonServerProcessError: User Rate Limit Exceeded

[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();
    }
}

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit ExceededjsonReaderError: User Rate Limit Exceeded

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

Error: User Rate Limit Exceededhttp://localhost:1092/Error: User Rate Limit ExceededurlError: User Rate Limit ExceededdataError: User Rate Limit Exceededdata: "{}"Error: User Rate Limit Exceededtype: "POST"Error: User Rate Limit ExceededajaxGridOptionsError: User Rate Limit Exceededmtype: "POST"Error: User Rate Limit Exceeded

$(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"
    });
});

Error: User Rate Limit Exceeded

UPDATEDError: User Rate Limit ExceededjsonReaderError: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

enter image description here

Error: User Rate Limit Exceeded

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; }
    }
}

Error: User Rate Limit Exceeded

$("#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
Error: User Rate Limit Exceeded<string xmlns="http://tempuri.org/"> Shantanu Gupta
Error: User Rate Limit Exceededroot: function (obj) { return obj.d; }, records: function (obj) { return obj.d.length; }Error: User Rate Limit ExceededjsonReaderError: User Rate Limit Exceededhere.
you should never use http://localhost:1092/ prefix in Ajax urlError: User Rate Limit Exceeded Shantanu Gupta
Error: User Rate Limit Exceededsame origin policyError: User Rate Limit Exceededanother host or another port as the host or port from which you make the requestError: User Rate Limit Exceededhttp://localhost:1092/Error: User Rate Limit Exceededthe sameError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded<string xmlns="http://tempuri.org/">Error: User Rate Limit Exceeded
1

Error: User Rate Limit Exceeded

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;
Error: User Rate Limit Exceeded
-1

Error: User Rate Limit Exceeded

[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);

    }
}
Error: User Rate Limit Exceeded
-1

Error: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

$.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;

Похожие вопросы