gpt4 book ai didi

.NET ASMX - 返回纯 JSON?

转载 作者:行者123 更新时间:2023-12-04 17:13:51 27 4
gpt4 key购买 nike

我要疯了。我查看了以下条目和 他们中的一些人正在纠正我看到的异常行为:

  • How to return JSON from a 2.0 asmx web service
  • How to return JSON from ASP.NET .asmx?
  • How to let an ASMX file output JSON

  • 我还查看并确认了我的设置: http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx

    这是我的代码(后面的 ASMX 代码):
    namespace RivWorks.Web.Services
    {
    /// <summary>
    /// Summary description for Negotiate
    /// </summary>
    [WebService(Namespace = "http://rivworks.com/webservices/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [ScriptService]
    public class Negotiate : System.Web.Services.WebService
    {
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public RivWorks.Data.Objects.rivProduct GetSetup(string jsonInput)
    {
    // Deserialize the input and get all the data we need...
    // TODO: This is a quick hack just to work with this for now...
    char[] tokens = { '(', '{', '}', ')', ',', '"' };
    string[] inputs = jsonInput.Split(tokens);
    string inputRef = "";
    string inputDate = "";
    string inputProductID = "";
    for (int i = 0; i < inputs.Length; i++)
    {
    if (inputs[i].Equals("ref", StringComparison.CurrentCultureIgnoreCase))
    inputRef = inputs[i+2];
    if (inputs[i].Equals("dt", StringComparison.CurrentCultureIgnoreCase))
    inputDate = inputs[i+2];
    if (inputs[i].Equals("productid", StringComparison.CurrentCultureIgnoreCase))
    inputProductID = inputs[i+2];
    }

    Guid pid = new Guid(inputProductID);
    RivWorks.Data.Objects.rivProduct product = RivWorks.Data.rivProducts.GetProductById(pid);

    return product;
    }
    }

    当我从我的本地主机实例运行它时,我得到了这个结果集:
      <ResultSet>
    <uiType>modal</uiType>
    <width>775</width>
    <height>600</height>
    <swfSource>
    http://localhost.rivworks.com/flash/negotiationPlayer.swf
    </swfSource>
    <buttonConfig>
    http://cdn1.rivworks.com/Element/Misc/734972de-40ae-45f3-9610-5331ddd6e8f8/apple-logo-2.jpg
    </buttonConfig>
    </ResultSet>

    我错过了什么???

    注意:我使用的是 3.5 框架(或者至少我认为我的 web.config 中的所有内容都标记为 3.5.0.0)

    更新:我正在浏览该服务并使用该页面上的输入框。你可以在这里试试: http://dev.rivworks.com/services/Negotiate.asmx?op=GetSetup .我们还尝试从另一个站点上运行的基于 JS 的 Web 应用程序访问它(此特定服务的主要目的)。我这里没有代码。 (抱歉,测试表只能从 localhost 获得。)

    更新:我添加了以下测试页面 (JsonTest.htm) 以尝试查看来回发生了什么。我得到的只是一个 500 错误!我什至尝试附加到该过程并闯入我的服务。在 ASP 管道进入我的代码之前会引发 500 错误。
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Untitled Page</title>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">
    function sendReq() {
    alert("Before AJAX call");
    $.ajax(
    {
    type: "POST"
    , url: "http://kab.rivworks.com/Services/Negotiate.asmx/GetSetup"
    , data: "{ \"ref\":\"http://www.rivworks.com/page.htm\", \"dt\":\"Mon Dec 14 2009 10:45:25 GMT-0700 (MST)\", \"productId\":\"5fea7947-251d-4779-85b7-36796edfe7a3\" }"
    , contentType: "application/json; charset=utf-8"
    , dataType: "json"
    , success: GetMessagesBack
    , error: Failure
    }
    );
    alert("After AJAX call");
    }
    function GetMessagesBack(data, textStatus) {
    alert(textStatus + "\n" + data);
    }
    function Failure(XMLHttpRequest, textStatus, errorThrown) {
    alert(textStatus + "\n" + errorThrown + "\n" + XMLHttpRequest);
    }
    </script>
    </head>
    <body>
    <div id="test">Bleh</div>
    <a href="javascript:sendReq()">Test it</a>
    </body>
    </html>

    为什么这么痛苦?!?! :)

    更新:通过 WCF 服务工作。这是我的设置:
    界面:
    namespace RivWorks.Web.Services
    {
    [ServiceContract(Name = "Negotiater", Namespace = "http://www.rivworks.com/services")]
    public interface INegotiaterJSON
    {
    //[WebMethod]
    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    ResultSet GetSetup(string jsonInput);
    }
    }

    类(class):
    namespace RivWorks.Web.Services
    {
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Negotiater : INegotiaterJSON
    {
    public ResultSet GetSetup(string jsonInput)
    {
    //code removed for brevity - see ASMX code above if you are really interested.
    return resultSet;
    }
    }


    [DataContract()]
    public class ResultSet
    {
    [DataMember]
    public string uiType = "modal";
    [DataMember]
    public int width = 775;
    [DataMember]
    public int height = 600;
    [DataMember]
    public string swfSource = "";
    [DataMember]
    public string buttonConfig = "";
    }
    }

    网络配置
      <system.serviceModel>
    <bindings>
    <basicHttpBinding>
    <binding name ="soapBinding">
    <security mode="None" />
    </binding>
    </basicHttpBinding>
    <webHttpBinding>
    <binding name="webBinding">
    <security mode="None" />
    </binding>
    </webHttpBinding>
    </bindings>
    <behaviors>
    <endpointBehaviors>
    <behavior name="poxBehavior">
    <webHttp/>
    </behavior>
    <behavior name="jsonBehavior">
    <enableWebScript />
    </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
    <behavior name="defaultBehavior">
    <serviceDebug includeExceptionDetailInFaults="true" />
    <serviceMetadata httpGetEnabled="true" />
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <services>
    <service name="RivWorks.Web.Services.Negotiater" behaviorConfiguration="defaultBehavior">
    <endpoint address="json"
    binding="webHttpBinding"
    bindingConfiguration="webBinding"
    behaviorConfiguration="jsonBehavior"
    contract="RivWorks.Web.Services.INegotiaterJSON" />
    </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true">
    <baseAddressPrefixFilters>
    <add prefix="http://dev.rivworks.com" />
    </baseAddressPrefixFilters>
    </serviceHostingEnvironment>
    </system.serviceModel>

    简单的测试页面
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Untitled Page</title>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">
    function sendReq() {
    alert("Before AJAX call");
    $.ajax(
    {
    type: "POST"
    , url: "http://dev.rivworks.com/Services/Negotiater.svc/GetSetup"
    , data: "{ \"ref\":\"http://www.rivworks.com/page.htm\", \"dt\":\"Mon Dec 14 2009 10:45:25 GMT-0700 (MST)\", \"productId\":\"5fea7947-251d-4779-85b7-36796edfe7a3\" }"
    , contentType: "application/json; charset=utf-8"
    , dataType: "json"
    , success: GetMessagesBack
    , error: Failure
    }
    );
    alert("After AJAX call");
    }
    function GetMessagesBack(data, textStatus) {
    alert(textStatus + "\n" + data);
    }
    function Failure(XMLHttpRequest, textStatus, errorThrown) {
    alert(textStatus + "\n" + errorThrown + "\n" + XMLHttpRequest);
    }
    </script>

    </head>
    <body>
    <div id="test">Bleh</div>
    <!--<button onclick="javascript:sendReq()">TEST IT</button>-->
    <a href="javascript:sendReq()">Test it</a>
    </body>
    </html>

    现在我收到了这个错误:
    IIS 指定身份验证方案“IntegratedWindowsAuthentication, Anonymous”,但绑定(bind)仅支持指定一个身份验证方案。有效的身份验证方案是 Digest、Negotiate、NTLM、Basic 或 Anonymous。更改 IIS 设置,以便只使用一个身份验证方案。

    我该如何处理? <状态情绪='筋疲力尽'体力='殴打'/>

    最佳答案

    为什么不将您的 ASMX Web 服务迁移到 WCF?

    .NET Framework 3.5 中的 WCF API 原生支持 JSON Web 服务。

    此外,微软宣布 ASMX 为“遗留技术”,并建议“现在应该使用 Windows Communication Foundation (WCF) 创建 Web 服务和 XML Web 服务客户端”。 (Source)。

    您可能需要查看以下链接以开始使用:

  • JSON-Enabled WCF Services in ASP.NET 3.5
  • REST Service with WCF and JSON
  • Creating a JSON Service with WebGet and WCF 3.5
  • Microsoft WCF REST Starter Kit
  • Hosting and Consuming WCF Services

  • 此外,您可能还想通读以下我从我的自托管 WCF 项目中“提取”的示例。自承载 WCF 服务不需要 IIS,但可以从任何托管的 .NET 应用程序提供服务。此示例托管在一个非常简单的 C# 控制台应用程序中:

    IContract.cs
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;

    namespace MyFirstWCF
    {
    [ServiceContract]
    public interface IContract
    {
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/CustomerName/{CustomerID}")]
    string GET_CustomerName(string CustomerID);
    }
    }

    服务.cs
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Syndication;
    using System.ServiceModel.Web;

    namespace MyFirstWCF
    {
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.NotAllowed)]
    public class Service : IContract
    {
    public string GET_CustomerName(string CustomerID)
    {
    return "Customer Name: " + CustomerID;
    }
    }
    }

    WCFHost.cs (控制台应用程序)
    using System;
    using System.Collections.Generic;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.ServiceModel.Description;
    using System.Threading;
    using System.Text;

    namespace MyFirstWCF
    {
    class Program
    {
    private static WebServiceHost M_HostWeb = null;

    static void Main(string[] args)
    {
    M_HostWeb = new WebServiceHost(typeof(MyFirstWCF.Service));

    M_HostWeb.Open();

    Console.WriteLine("HOST OPEN");
    Console.ReadKey();

    M_HostWeb.Close();
    }
    }
    }

    应用程序配置
    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>
    <system.serviceModel>
    <services>
    <service name="MyFirstWCF.Service">

    <endpoint address="http://127.0.0.1:8000/api"
    binding="webHttpBinding"
    contract="MyFirstWCF.IContract" />

    </service>
    </services>

    </system.serviceModel>
    </configuration>

    上面的例子非常基础。如果您使用 Fiddler 构建请求至 http://127.0.0.1:8000/api/CustomerName/1000它只会返回 "Customer Name: 1000" .

    确保设置 content-type: application/json在请求头中。要返回更复杂的数据结构,您将不得不使用数据协定。它们的构造如下:
    [DataContract]
    public class POSITION
    {
    [DataMember]
    public int AssetID { get; set; }

    [DataMember]
    public decimal Latitude { get; set; }

    [DataMember]
    public decimal Longitude { get; set; }
    }

    您需要将 .NET 引用添加到 System.RuntimeSerialization , System.ServiceModelSystem.ServiceModel.Web用于编译此示例项目。

    关于.NET ASMX - 返回纯 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1903022/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com