Question

i am writing a web method to return an html file to android client here is the code i have tried

 [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;

}
}

and defiantly its not working, i am not sure about the return type of the method, which to choose. do i need to convert that html file to string and then return it to client?

Was it helpful?

Solution

Your initial post returns without doing anything else at the first line:

return "Hello World";

Remove this line if you want the rest of it to work.

In order to return the contents of the file, just do a File.ReadAll:

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

EDIT:

In order to send a file to the client, you need to send the file's bytes AND set the proper headers. This has already been answered here. You need to set the content type, content disposition and content length headers. You need to write something like this:

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();

Just calling Response.WriteFile isn't enough because you need to set the proper headers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top