【问题标题】:How to call a web service with .ashx extention in C# MVC?如何在 C# MVC 中调用具有 .ashx 扩展名的 Web 服务?
【发布时间】:2015-11-06 09:34:46
【问题描述】:

想要调用扩展名为 .aspx 的 Web 服务。它无法添加到网络引用中。然后我使用了 webclient 并返回字符串。但是后来我不知道如何使用它。这是我的代码。

 WebClient client = new WebClient();

 detail.Title = client.DownloadString("https://somename/cruiseproducts.ashx");
 return downloadedString;

【问题讨论】:

    标签: c# xml asp.net-mvc-4 ashx


    【解决方案1】:

    这取决于你的服务返回什么

    例如

    你的 ashx 服务应该是这样的

    public class TestHandler : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    

    你的客户端代码应该是这样的

    WebClient client = new WebClient();
    
    var testResult = client.DownloadString("http://localhost:19238/TestHandler.ashx");
        return testResult;
    

    通知服务正在返回"plain/text" 类型

    如果服务返回 xml 类型,那么你可以简单地先获取字符串,然后像这样解析

    //consider that result is in testResult variable
    var xml = new XmlDocument();
    
    //your xml tree
    xml.LoadXml(testResult);
    

    【讨论】:

    • 没有添加 ashx 处理程序我得到了结果。那怎么用呢,因为它不会出现xml标签。并感谢您的回复@Gtopuria
    • 我没有使用任何处理程序@Gtopuria
    • 服务xml返回什么类型?你想解析还是有什么问题?
    • *当我们在浏览器中输入 url 时,它会显示 xml 内容。 *然后它返回不带标签的整个 xml 内容。这意味着纯文本
    • 如果您的服务返回 xml,那么您必须创建 XmlDocument 变量,然后使用函数 LoadXml() 这会将您返回的字符串解析为 xml,我将更新答案
    猜你喜欢
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2014-07-03
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多