У меня есть приложение Silverlight, размещенное на сайте ASP.NET, через которое я запускаю HttpWebRequest для универсального обработчика, чтобы сохранить файл CSV на компьютере пользователя.
В приложении Silverlight создается Uri с параметрами, чтобы сделать CSV-файл на стороне сервера. Нажимается кнопка, которая вызывает следующее:
string httpHandlerName = "HttpDownloadHandler.ashx";
// CustomUri handles making it an absolute Uri wherever we move the handler.
string uploadUrl = new CustomUri(httpHandlerName).ToString();
UriBuilder httpHandlerUrlBuilder = new UriBuilder(uploadUrl);
httpHandlerUrlBuilder.Query = string.Format("{3}startdate={0}&enddate={1}&partnerId={2}", startDate, endDate, partnerId, string.IsNullOrEmpty(httpHandlerUrlBuilder.Query) ? "" : httpHandlerUrlBuilder.Query.Remove(0, 1) + "&");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(httpHandlerUrlBuilder.Uri);
webRequest.Method = "POST";
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
Теперь вот код ProcessRequest из HttpDownloadHandler.ashx
public void ProcessRequest(HttpContext context)
{
_httpContext = context;
string partnerId = _httpContext.Request.QueryString["partnerId"];
string startDate = _httpContext.Request.QueryString["startDate"];
string endDate = _httpContext.Request.QueryString["endDate"];
ExportCsvReport exportCsv = new ExportCsvReport();
_csvReport = exportCsv.ExportMemberRegistrationReport(partnerId, startDate, endDate);
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment; filename=Report.csv");
context.Response.ContentType = "text/csv";
context.Response.Write(_csvReport);
}
Вот информация заголовка HttpResponse, которая возвращается, когда диалоговое окно сохранения файла отказывается появляться:
{System.Web.HttpResponse}
Buffer: true
BufferOutput: true
Cache: {System.Web.HttpCachePolicy}
CacheControl: "private"
Charset: "utf-8"
ContentEncoding: {System.Text.UTF8Encoding}
ContentType: "text/csv"
Cookies: {System.Web.HttpCookieCollection}
Expires: 0
ExpiresAbsolute: {1/1/0001 12:00:00 AM}
Filter: {System.Web.HttpResponseStreamFilterSink}
HeaderEncoding: {System.Text.UTF8Encoding}
Headers: 'context.Response.Headers' threw an exception of type 'System.PlatformNotSupportedException'
IsClientConnected: true
IsRequestBeingRedirected: false
Output: {System.Web.HttpWriter}
OutputStream: {System.Web.HttpResponseStream}
RedirectLocation: null
Status: "200 OK"
StatusCode: 200
StatusDescription: "OK"
SubStatusCode: 'context.Response.SubStatusCode' threw an exception of type 'System.PlatformNotSupportedException'
SuppressContent: false
TrySkipIisCustomErrors: false
Когда я перехожу к localhost/HttpDownloadHandler.ashx, когда сайт работает, не инициируя его из приложения Silverlight, диалоговое окно «Сохранить файл» отображается просто отлично, похоже, это тот случай, когда Silverlight не принимает заголовок ответа должным образом.
Можно ли что-нибудь сделать, чтобы решить эту проблему? Я открыт для предложений по изменению того, как я это делаю, конечно.