从ASP.NET发送文件到桌面应用程序(客户端)

时间:2015-01-05 17:53:59

标签: c# asp.net httprequest httpresponse

我正在为桌面应用程序开发许可。一个简单的工作流程:

  1. 用户的详细信息通过HttpPost方法提交给服务器(或其他)
  2. 服务器检查详细信息并生成文件。
  3. 服务器向用户发送文件(作为确认)
  4. 我需要步骤3-如何向用户发送文件?

    例如,用户(HttpPost)

    var client = new HttpClient();
    
    var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("serialNumber", "AAAA"),
        new KeyValuePair<string, string>("email", "test@123"),
        new KeyValuePair<string, string>("HWID", "AAAA-BBBB-CCCC-DDDD"),
    };
    
    var content = new FormUrlEncodedContent(pairs);
    
    var response = client.PostAsync("https://localhost:44302/testCom.aspx", content).Result;
    
    if (response.IsSuccessStatusCode)
    {
        //Code for file receiving?
    
    }
    

    服务器

    protected void Page_Load(object sender, EventArgs e)
    {
                //Check license ID
    
                //Issue license file - How to?
    
                //Mark database
    }
    

2 个答案:

答案 0 :(得分:1)

您可以使用Response类将文件发送回客户端

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

答案 1 :(得分:1)

private void sendFile(string path, string fileName)
{
    FileStream fs = new FileStream(path, FileMode.Open);
    streamFileToUser(fs, fileName);
    fs.Close();
}

private void streamFileToUser(Stream str, string fileName)
{
    byte[] buf = new byte[str.Length];  //declare arraysize
    str.Read(buf, 0, buf.Length);

    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    HttpContext.Current.Response.AddHeader("Content-Length", str.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.OutputStream.Write(buf, 0, buf.Length);
    HttpContext.Current.Response.End();
}