关于Web服务:ASP.NET-Web方法的响应可以是SOAP(XML)和JSON吗?

ASP.NET - Can a web method's response be SOAP (XML) and JSON?

我有一个ASP.NET Web应用程序。

它具有一个Web服务,其中包含几种Web方法。

所有这些Web方法均基于默认设置。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Web.Services;

namespace WebApplication2
{
    [WebService(Namespace ="http://mydomain.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class WebService1 : WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return"Hello World";
        }

        [WebMethod]
        public Person GetPersonById(int id)
        {
            Person result = new Person();
            // code...
            return person;
        }
    }
}

响应为SOAP(XML)格式。

我的问题:是否可以基于输入参数或标头将响应的格式更改为JSON?


ASMX Web服务的响应类型由单个Web方法上的ResponseFormat属性指定。

例如:

1
2
3
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public Person GetPersonById(int id)

1
2
3
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Person GetPersonById(int id)

所以AFAIK答案是否定的-您不能同时返回两者(从一种方法)。

我确定您可以做一些破解,但这是推荐的方法。

如果要开始同时返回这两种类型,则应使用WCF REST,OData或ASP.NET MVC,采用更RESTful的方法。

在这些技术中,被叫方可以指定他们希望的响应类型:

GET: http://api.yourdomain.com/person/1?format=json

GET: http://api.yourdomain.com/person/1?format=xml

请注意两个呼叫如何都是一种物理资源。

在旁注中,出于安全原因,此处的" The Goo"提到了您的JSON Web服务调用应为HTTP POST。


从技术上讲,是的,您只需发送回Json并将Response的Content-Type设置为" application / json"。


您应该签出Windows Communication Foundation(WCF)。使用它可以定义服务的多个端点。这些端点中的每个端点都可以例如以不同的格式返回数据。

WCF服务的REST / SOAP端点