prosource

asp.net asmx 웹 서비스가 json 대신 xml을 반환함

probook 2023. 2. 12. 18:02
반응형

asp.net asmx 웹 서비스가 json 대신 xml을 반환함

이 간단한 웹 서비스는 왜 클라이언트에 대한 JSON 반환을 거부합니까?

클라이언트 코드는 다음과 같습니다.

        var params = { };
        $.ajax({
            url: "/Services/SessionServices.asmx/HelloWorld",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            timeout: 10000,
            data: JSON.stringify(params),
            success: function (response) {
                console.log(response);
            }
        });

서비스 내용:

namespace myproject.frontend.Services
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class SessionServices : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

web.config:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

그리고 응답:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

어떤 작업을 수행해도 항상 XML로 응답이 반환됩니다. 웹 서비스에서 Json을 반환하려면 어떻게 해야 합니까?

편집:

다음으로 Fiddler HTTP 트레이스를 나타냅니다.

REQUEST
-------
POST http://myproject.local/Services/SessionServices.asmx/HelloWorld HTTP/1.1
Host: myproject.local
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://myproject.local/Pages/Test.aspx
Content-Length: 2
Cookie: ASP.NET_SessionId=5tvpx1ph1uiie2o1c5wzx0bz
Pragma: no-cache
Cache-Control: no-cache

{}

RESPONSE
-------
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 19 Jun 2012 16:33:40 GMT
Content-Length: 96

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

나는 이것을 고치려고 지금 얼마나 많은 기사를 읽었는지 셀 수 없었다.설명이 불완전하거나 어떤 이유로든 문제가 해결되지 않습니다.보다 관련성이 높은 것 중 몇 가지는 다음과 같습니다(모두 성공하지 못한 경우).

그리고 다른 일반 기사도 몇 개 더 있습니다.

드디어 알아냈어

앱 코드는 게시된 대로 정확합니다.설정에 문제가 있다.올바른 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에 등록하면 문제가 해결되었습니다.

를 에 .<system.web> 다른 문제가 합니다.이것은 동작하지 않고, 그 외의 많은 문제를 일으킵니다.양쪽 섹션에 핸들러를 추가하려고 하면 다른 일련의 이행 에러가 발생하여 트러블 슈팅이 완전히 잘못되어 버립니다.

만약 다른 사람에게 도움이 된다면, 또 같은 문제가 생긴다면, 체크리스트를 확인해 보겠습니다.

  1. type: "POST"AJAX?
  2. contentType: "application/json; charset=utf-8"AJAX?
  3. dataType: "json"AJAX?
  4. 웹 에는 .asmx가 ?[ScriptService]속??
  5. 하시는 웹 에 ""가 ?[ScriptMethod(ResponseFormat = ResponseFormat.Json)] (내 많은 기사에서는 필수라고 합니다.)
  6. 추가되었습니까?ScriptHandlerFactory의 web.config 파일로 이동합니다.<system.webServer><handlers>?
  7. 의 web.config 파일에서 모든 핸들러를 삭제했습니까?<system.web><httpHandlers>?

이것이 같은 문제를 가진 사람에게 도움이 되기를 바랍니다.포스터에 제안해 주셔서 감사합니다.

위의 솔루션으로는 성공하지 못했습니다.여기서 해결 방법을 설명하겠습니다.

이 행을 웹 서비스에 삽입하고 반환 유형을 반환하는 대신 응답 컨텍스트에 문자열을 입력하십시오.

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

Framework 3.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);
    }
}

웹 서비스에서 순수 문자열을 반환하는 훨씬 쉬운 방법이 있습니다.나는 그것을 CROW 함수라고 부른다(기억하기 쉽다).

  [WebMethod]
  public void Test()
    {
        Context.Response.Output.Write("and that's how it's done");    
    }

보시다시피 반환 유형은 "void"이지만 CROW 함수는 원하는 값을 반환합니다.

.asmx 웹 서비스(.문자열을 반환하는 메서드를 사용하는 NET 4.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;

서비스를 사용하는 클라이언트 부분은 다음과 같습니다.

   $.ajax({
       type: 'POST',
       contentType: "application/json; charset=utf-8",
       dataType: 'json',
       url: 'http://localhost:54253/TmsWebService.asmx/GetTombstoneDataJson',
       data: "{'ObjectNumber':'105.1996'}",
       success: function (data) {
           alert(data.d);
       },
       error: function (a) {
           alert(a.responseText);
       }
   });

이것이 도움이 되기를 바랍니다.콜하고 있는 메서드에 파라미터가 없는 경우에도 요청 내의 일부 JSON 오브젝트를 송신할 필요가 있는 것 같습니다.

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

저는 이 게시물에서 얻은 다음 코드로 작동합니다.

WCF rest 서비스(.)에서 json을 반환하려면 어떻게 해야 합니까?NET 4), Json을 사용합니다.끈이 없이 따옴표로 둘러싸인 넷?

[WebInvoke(UriTemplate = "HelloWorld", Method = "GET"), OperationContract]
public Message HelloWorld()
{
    string jsonResponse = //Get JSON string here
    return WebOperationContext.Current.CreateTextResponse(jsonResponse, "application/json; charset=utf-8", Encoding.UTF8);
}

위의 순서(답변도)를 모두 시험해 보았습니다만, 성공하지 못했습니다.시스템 구성은 Windows Server 2012 R2, IIS 8 입니다.다음 단계로 문제가 해결되었습니다.

관리 파이프라인 = classic이 있는 앱 풀을 변경했습니다.

정말 오래된 질문인 건 알지만 오늘 같은 문제에 직면해서 답을 찾기 위해 사방을 뒤졌지만 아무 결과도 없었다.오랜 연구 끝에 나는 이 일을 해낼 방법을 찾았다.요청 시 올바른 형식으로 데이터를 제공한 서비스에서 JSON을 반환하려면 다음을 사용하십시오.JSON.stringify()데이터를 분석하기 전에 잊지 말고contentType: "application/json; charset=utf-8"이를 사용하면 예상되는 결과를 얻을 수 있습니다.

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;

언급URL : https://stackoverflow.com/questions/11088294/asp-net-asmx-web-service-returning-xml-instead-of-json

반응형