【问题标题】:WebMethod to return an html fileWebMethod 返回一个 html 文件
【发布时间】:2014-03-19 12:18:43
【问题描述】:

我正在编写一个 web 方法来将一个 html 文件返回给 android 客户端 这是我尝试过的代码

 [WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]



public class Service1 : System.Web.Services.WebService

{

[WebMethod]
public string HelloWorld()
{

    string file = Server.MapPath("index.html");
    return file;

}
}

而且毫无疑问它不起作用,我不确定该方法的返回类型,该选择哪个。 我需要将该html文件转换为字符串然后返回给客户端吗?

【问题讨论】:

  • 您是要返回文件的内容,还是文件的URL
  • 我需要将整个html文件下载到客户端,这是一个android设备。
  • ASMX 是一项遗留技术,不应用于新开发。 WCF 或 ASP.NET Web API 应该用于 Web 服务客户端和服务器的所有新开发。一个提示:Microsoft 已停用 MSDN 上的 ASMX Forum

标签: c# asmx


【解决方案1】:

你的初始帖子在第一行没有做任何其他事情就返回了:

return "Hello World";

如果您希望其余部分正常工作,请删除此行。

为了返回文件的内容,只需做一个File.ReadAll:

string filePath = Server.MapPath("index.html");
string content=File.ReadAll(filePath);
return content;

编辑

为了向客户端发送文件,您需要发送文件的字节并设置正确的标题。这已经回答了here。您需要设置内容类型、内容处置和内容长度标头。你需要这样写:

var fileBytes=File.ReadAllBytes(filePath);

Response.Clear();
Response.ClearHeaders();
Response.ContentType = "text/html; charset=UTF-8";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filePath + "\"");
Response.AddHeader("Content-Length", fileBytes.Length);
Response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
Response.Flush();
Response.End();

仅调用 Response.WriteFile 是不够的,因为您需要设置正确的标头

【讨论】:

  • 感谢回复,但是如果我想返回整个文件,而不是文件的内容呢?
  • 已回答here。您需要返回一个设置正确标头的字节数组,以便客户端了解您正在将文件作为附件发送
猜你喜欢
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2012-07-11
  • 2013-05-07
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
相关资源
最近更新 更多