【问题标题】:Send XML String as Response发送 XML 字符串作为响应
【发布时间】:2011-02-26 05:09:29
【问题描述】:

我的请求从第三方应用程序(不同的域)到我的 ASP 应用程序。我正在处理请求并在我的应用程序中执行业务部分,作为确认,我需要将 XML 字符串作为响应发送到将请求发布到我的应用程序的同一页面。我成功地使用以下代码从 Request 中检索了输入

  NameValueCollection postPageCollection = Request.Form;
  foreach (string name in postPageCollection.AllKeys)
    {
        ... = postPageCollection[name]);
    }

但我不确定如何将响应与 XML 字符串一起发送回站点(不同的域)?

编辑:如何从 POST 发生的地方获取 URL。

【问题讨论】:

    标签: c# asp.net request cross-domain response


    【解决方案1】:

    你不能只使用以下代码:

    Request.UrlReferrer.ToString();
    

    【讨论】:

    • 我发现 Request.UrlReferrer 为 NULL。我从保存到本地磁盘的 HTML 文件发布。
    【解决方案2】:

    您可以获取来自 Request.ServerVariables["HTTP_REFERER"]

    的 url

    对于 XML,这里有 2 个我使用的函数

    public static string ObjectToXML(Type type, object obby)
    {
        XmlSerializer ser = new XmlSerializer(type);
        using (System.IO.MemoryStream stm = new System.IO.MemoryStream())
        {
            //serialize to a memory stream
            ser.Serialize(stm, obby);
            //reset to beginning so we can read it.  
            stm.Position = 0;
            //Convert a string. 
            using (System.IO.StreamReader stmReader = new System.IO.StreamReader(stm))
            {
                string xmlData = stmReader.ReadToEnd();
                return xmlData;
            }
        }
    }
    
    public static object XmlToObject(Type type, string xml)
    {
        object oOut = null;
    
        //hydrate based on private string var
        if (xml != null && xml.Length > 0)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
    
            using (System.IO.StringReader sReader = new System.IO.StringReader(xml))
            {
                oOut = serializer.Deserialize(sReader);
    
                sReader.Close();
            }
        }
    
        return oOut;
    }
    

    这是我如何使用它的示例

    [Serializable]
    public class MyClassThatKeepTheData
    {
        public int EnaTest;
    }
    
    MyClassThatKeepTheData cTheObject = new MyClassThatKeepTheData();
    
    ObjectToXML(typeof(MyClassThatKeepTheData), cTheObject)
    

    【讨论】:

    • 如何返回带有 XML 字符串的响应?
    • @Sri 有很多方法可以返回 xml,一种是创建一个 .ashx 文件,然后在其中输入。您的客户只需要索要此文件。其他方式取决于您的协议。如果您的客户要求您提供一页 (.aspx),您只需在此页中键入 xml。
    猜你喜欢
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    相关资源
    最近更新 更多