如何阻止 ASP.NET Web 服务返回 xml 数据?

发布于 2024-08-01 13:36:51 字数 526 浏览 4 评论 0原文

我有一个简单的 ASP.NET Web 服务。 我想返回一个 json 字符串作为结果。 默认情况下,我的 Web 服务将我的 json 结果包装在一些 xml 中。

例如。

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://webservice.streetadvisor.com/">{.... json result in here ... }</string>

嘘。

  • 有什么方法可以让我的 web 服务不返回一些 xml,而只是将我的结果写为原始输出?
  • 我可以在 Web 服务中定义 HTTP-StatusCode 吗? 例如。 200、201、202、404、500 等?
  • 我可以定义响应类型吗? 例如。 application/json

干杯!

I've got a simple ASP.NET webservice. I'm wanting to return a string of json as the result. By default, my webservice is wrapping my json result in some xml.

eg.

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://webservice.streetadvisor.com/">{.... json result in here ... }</string>

Booo.

  • Is there any way i can make my webservice NOT return some xml, but just write my result as raw output?
  • Can I define the HTTP-StatusCode in the webservice? eg. 200, 201, 202, 404, 500, etc?
  • Can i define the response type? eg. application/json

Cheers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独闯女儿国 2024-08-08 13:36:51

您可以通过创建 .ashx 处理程序而不是普通的 Web 服务来相当轻松地完成此操作 - 但此时您会失去许多围绕 Web 服务的基础设施,特别是以 SOAP 所采用的结构化方式解释来自客户端的数据的任何内容。给你。

以下是创建 RSS feed 作为“raw”处理程序,这里有一个更一般的教程。 这并不是特别棘手 - 如果这些对您没有多大帮助,请搜索 ashx,您会得到很多结果。

不过,我不知道从 Web 服务项目中做到这一点有多容易 - 我只从直接的 ASP.NET Web 应用程序项目中做到了这一点。 不过,它很可能“有效”——值得一试。

You can do this fairly easily by creating a .ashx handler instead of a normal web service - but at that point you lose a lot of the infrastructure around web services, in particular anything interpreting the data coming from the client in the structured way that SOAP gives you.

Here's an example of creating an RSS feed as a "raw" handler, and here's a more general tutorial. It's not particularly tricky - if those don't help you much, do a search for ashx and you'll get lots of hits.

I don't know how easy it is to do from a web service project though - I've only done it from a straight ASP.NET web application project. It may well "just work" though - it's worth a try.

你在看孤独的风景 2024-08-08 13:36:51

有时,如果我想返回 JSON,我只需使用 .aspx 页面:

Response.Clear();
Response.ContentType = "text/javascript";

然后使用 .NET Json 框架(如 1 这里)我创建了我希望它返回的json。

Sometimes if im wanting to return JSON i just use a .aspx page with:

Response.Clear();
Response.ContentType = "text/javascript";

Then using a .NET Json framework (like the 1 here) i create the json i want it to return.

千柳 2024-08-08 13:36:51

您可以简单地使用

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]

这对我有用。

You can simply use

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]

This worked for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文