Skip to main content
 首页 » 编程设计

c#之如何在 C# MVC 中调用扩展名为 .ashx 的 Web 服务

2024年05月22日50zhengyun_ustc

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

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

请您参考如下方法:

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

例如

你的 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);