【发布时间】:2020-06-02 14:30:43
【问题描述】:
我正在尝试设置 asmx 服务以在 Web 方法中返回 json。当我查看里面的响应时 浏览器而不是返回 json 我得到 xml。我已经设置了我的 web 方法来返回 json 格式。 请在下面找到我的网络服务:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace space_port_lander_real_app
{
/// <summary>
/// Summary description for WebService1
/// </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 WebService1 : System.Web.Services.WebService
{
[WebMethod(CacheDuration = 60)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
//string xmlstring = "<user><name>Hello World</name><password>some pass</password></user>";
//var name = $(xml).find('name').text();
//return xmlstring;
return "hello world";
}
}
}
响应输出如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">hello world</string>
我将我的方法设置为返回一个字符串。我有什么遗漏吗?
【问题讨论】:
-
旁注:为什么是 asmx 服务?为什么不使用 web api 呢?
-
如果你改变你的方法来返回一个对象会发生什么?示例:
public object HelloWorld() { return new {Message = "hellow world"}; } -
您的请求的
content-type标头是什么?如果我没记错的话,如果标头没有另外指定,ASMX 服务总是返回 XML... -
你只能得到服务器设计返回的东西。一些服务器将返回 xml、一些 json 和一些两者。当它同时支持时,你可能需要在请求中添加一个参数来指定返回格式。
-
如果从 System.Web.Services.WebService 继承,您正在创建一个肥皂服务,或者这些天我猜它称为 Xml Web 服务。