【问题标题】:Remove xml header from C# webservice从 C# webservice 中删除 xml 标头
【发布时间】:2015-07-21 11:38:05
【问题描述】:

我需要使用 C# webservice 构建一个 API,它需要以 json 格式返回值。

目前我有以下几行代码

namespace WebService1
{
    /// <summary>
    /// Summary description for Service1
    /// </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 Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return new JavaScriptSerializer().Serialize(new { errMsg = "test" });
        }
    }
}

调用post方法时this的输出是

<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://tempuri.org/">{"errMsg":"test"}</string>

但这不是一个有效的 json 如何让 web 服务只返回 json 对象而不是 xml 标头?

【问题讨论】:

  • 你考虑过使用asp.net web api吗?

标签: c# json web-services


【解决方案1】:

使用标头 Content-Type: application/json 调用此 Web 服务将自动将响应转换为 json,并且您的 xml 将消失。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多