WebMethod返回一个html文件

时间:2014-03-19 12:18:44

标签: c# asmx

我正在编写一个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文件转换为字符串,然后将其返回给客户端吗?

1 个答案:

答案 0 :(得分:3)

您的初始帖子在第一行没有做任何其他操作时返回:

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是不够的,因为你需要设置正确的标题