Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# asp.net asmx web服务返回xml而不是json_C#_Asp.net_Json_Web Services_Asmx - Fatal编程技术网

C# asp.net asmx web服务返回xml而不是json

C# asp.net asmx web服务返回xml而不是json,c#,asp.net,json,web-services,asmx,C#,Asp.net,Json,Web Services,Asmx,为什么这个简单的web服务拒绝将JSON返回给客户端 这是我的客户代码: var params={}; $.ajax({ url:“/Services/SessionServices.asmx/HelloWorld”, 类型:“POST”, contentType:“应用程序/json;字符集=utf-8”, 数据类型:“json”, 超时:10000, 数据:JSON.stringify(params), 成功:功能(响应){ 控制台日志(响应); } }); 以及服务: 名称空间mypro

为什么这个简单的web服务拒绝将JSON返回给客户端

这是我的客户代码:

var params={};
$.ajax({
url:“/Services/SessionServices.asmx/HelloWorld”,
类型:“POST”,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
超时:10000,
数据:JSON.stringify(params),
成功:功能(响应){
控制台日志(响应);
}
});
以及服务:

名称空间myproject.frontend.Services
{
[WebService(命名空间=”http://tempuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[脚本服务]
公共类会话服务:System.Web.Services.WebService
{
[网络方法]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
公共字符串HelloWorld()
{
返回“你好世界”;
}
}
}
web.config:


答复如下:


你好,世界
无论我做什么,响应总是以XML的形式返回。如何让web服务返回Json

编辑:

以下是Fiddler HTTP跟踪:

请求
-------
邮递http://myproject.local/Services/SessionServices.asmx/HelloWorld HTTP/1.1
主持人:myproject.local
用户代理:Mozilla/5.0(Windows NT 6.1;WOW64;rv:13.0)Gecko/20100101 Firefox/13.0.1
接受:application/json,text/javascript,*/*;q=0.01
接受语言:en-gb,en;q=0.5
接受编码:gzip,deflate
连接:保持活力
内容类型:application/json;字符集=utf-8
X-request-With:XMLHttpRequest
推荐人:http://myproject.local/Pages/Test.aspx
内容长度:2
Cookie:ASP.NET_SessionId=5tvpx1ph1uiie2o1c5wzx0bz
Pragma:没有缓存
缓存控制:没有缓存
{}
回应
-------
HTTP/1.1200ok
缓存控制:专用,最大年龄=0
内容类型:text/xml;字符集=utf-8
服务器:Microsoft IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
日期:2012年6月19日星期二格林尼治标准时间16:33:40
内容长度:96
你好,世界
我已经记不清我现在读了多少篇文章试图解决这个问题。说明不完整或由于某种原因无法解决我的问题。 一些更相关的问题包括(均未成功):


加上其他几篇一般性文章。

对我来说,它与我从这篇文章中获得的代码一起工作:


我终于明白了

应用程序代码正确无误。问题在于配置。正确的web.config是:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.webServer>
        <handlers>
            <add name="ScriptHandlerFactory"
                 verb="*" path="*.asmx"
                 type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                 resourceType="Unspecified" />
        </handlers>
    </system.webServer>
</configuration>

根据文档,从.NET 4向上注册处理程序应该是不必要的,因为它已被移动到machine.config。不管什么原因,这对我来说都不管用。但将注册添加到我的应用程序的web.config中解决了问题

关于这个问题的许多文章都指示将处理程序添加到
部分。这不起作用,并导致一大堆其他问题。我尝试将处理程序添加到这两个部分,这会生成一组其他迁移错误,这些错误完全误导了我的故障排除

如果这对其他人有帮助,如果我再次遇到同样的问题,下面是我要回顾的清单:

  • 您是否在ajax请求中指定了
    类型:“POST”
  • 您是否在ajax请求中指定了
    contentType:“application/json;charset=utf-8”
  • 您是否在ajax请求中指定了
    数据类型:“json”
  • .asmx web服务是否包含
    [ScriptService]
    属性
  • 您的web方法是否包括
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    
    属性?(我的代码即使没有这个属性也能工作,但很多文章都说它是必需的)
  • 您是否已将
    ScriptHandlerFactory
    添加到
    中的web.config文件中
  • 您是否已从中的web.config文件中删除了所有处理程序

  • 希望这能帮助有同样问题的人。感谢海报的建议。

    以上解决方案没有成功,下面是我如何解决的

    将这一行放到您的Web服务中,而不是返回类型,只需在响应上下文中编写字符串即可

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

    我有一个.asmxweb服务(.net4.0),它有一个返回字符串的方法。该字符串是一个序列化列表,就像您在许多示例中看到的那样。这将返回未包装为XML的json。不更改web.config或不需要第三方DLL

    var tmsd = new List<TmsData>();
    foreach (DataRow dr in dt.Rows)
    {
    
    m_firstname = dr["FirstName"].ToString();
    m_lastname = dr["LastName"].ToString();
    
    tmsd.Add(new TmsData() { FirstName = m_firstname, LastName = m_lastname} );
    
    }
    
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string m_json = serializer.Serialize(tmsd);
    
    return m_json;
    

    如果您想继续使用Framework3.5,您需要对代码进行如下更改

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        public WebService()
        {
        }
    
        [WebMethod]
        public void HelloWorld() // It's IMP to keep return type void.
        {
            string strResult = "Hello World";
            object objResultD = new { d = strResult }; // To make result similarly like ASP.Net Web Service in JSON form. You can skip if it's not needed in this form.
    
            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            string strResponse = ser.Serialize(objResultD);
    
            string strCallback = Context.Request.QueryString["callback"]; // Get callback method name. e.g. jQuery17019982320107502116_1378635607531
            strResponse = strCallback + "(" + strResponse + ")"; // e.g. jQuery17019982320107502116_1378635607531(....)
    
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.AddHeader("content-length", strResponse.Length.ToString());
            Context.Response.Flush();
    
            Context.Response.Write(strResponse);
        }
    }
    

    我已经尝试了以上所有步骤(甚至是答案),但没有成功,我的系统配置是Windows Server 2012 R2,IIS 8。下面的步骤解决了我的问题


    更改了管理pipeline=classic的应用程序池。

    有一种更简单的方法可以从web服务返回纯字符串。我称之为CROW函数(便于记忆)

    如您所见,返回类型为“void”,但CROW函数仍将返回所需的值。

    response=wait client.GetAsync(RequestUrl,HttpCompletionOption.ResponseContentRead);
    
    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;
    
    if(响应。IsSuccessStatusCode) { _data=wait response.Content.ReadAsStringAsync(); 尝试 { XmlDocument_doc=新的XmlDocument(); _doc.LoadXml(_数据); return Request.CreateResponse(HttpStatusCode.OK,JObject.Parse(_doc.InnerText)); } 捕获(异常jex) { return Request.CreateResponse(HttpStatusCode.BadRequest,jex.Message); } } 其他的 返回Task.FromResult(Request.CreateResponse(HttpStatusCode.NotFound)).Result;
    我知道这是一个很老的问题,但我还是来了
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        public WebService()
        {
        }
    
        [WebMethod]
        public void HelloWorld() // It's IMP to keep return type void.
        {
            string strResult = "Hello World";
            object objResultD = new { d = strResult }; // To make result similarly like ASP.Net Web Service in JSON form. You can skip if it's not needed in this form.
    
            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            string strResponse = ser.Serialize(objResultD);
    
            string strCallback = Context.Request.QueryString["callback"]; // Get callback method name. e.g. jQuery17019982320107502116_1378635607531
            strResponse = strCallback + "(" + strResponse + ")"; // e.g. jQuery17019982320107502116_1378635607531(....)
    
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.AddHeader("content-length", strResponse.Length.ToString());
            Context.Response.Flush();
    
            Context.Response.Write(strResponse);
        }
    }
    
      [WebMethod]
      public void Test()
        {
            Context.Response.Output.Write("and that's how it's done");    
        }
    
    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;
    
    var params = {};
    return $http({
            method: 'POST',
            async: false,
            url: 'service.asmx/ParameterlessMethod',
            data: JSON.stringify(params),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
    
        }).then(function (response) {
            var robj = JSON.parse(response.data.d);
            return robj;
        });