ASP.NET - Web方法的响应可以SOAP(XML)和JSON? [英] ASP.NET - Can a web method's response be SOAP (XML) and JSON?

查看:106
本文介绍了ASP.NET - Web方法的响应可以SOAP(XML)和JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an ASP.NET web application.

它有一个Web服务,有几个网站的方法。

It has a web service, with several web methods.

所有这些网络的方法是基于默认设置。例如:

All of these web methods are based on the default settings. For instance:

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)格式。

The response is in SOAP (XML) format.

我的问题:我可以改变响应的格式JSON的基础上,输入参数或在头

My question: Can I change the response's format to JSON, based on an input parameter or on a header?

推荐答案

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

The response type of a ASMX Web Service is specified by the ResponseFormat attribute on the individual web method.

例如:

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

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

所以据我所知,答案是否 - 你不能同时返回(从一种方法即是)

我敢肯定有一些黑客可以做,但这是推荐的方式。

I'm sure there are some hacks you can do, but this is the recommended way.

如果你想开始返回两种类型,你应该移到更RESTful方法,无论是与WCF REST,或者OData的ASP.NET MVC。

If you want to start returning both types, you should move to a more RESTful approach, either with WCF REST, OData or ASP.NET MVC.

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

In those technologies, the callee can specify the response type they wish:

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

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

请注意这两个调用是如何一个物理资源。

Note how both calls are one physical resource.

在一个侧面说明,你的JSON Web服务调用应 HTTP POST ,出于安全原因被提及的咕<一个href=\"http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx\"相对=nofollow>这里。

On a side note, your JSON web service calls should be HTTP POST, for security reasons mentions by "The Goo" here.

这篇关于ASP.NET - Web方法的响应可以SOAP(XML)和JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆