Làm cách nào để lấy các tham số Nội dung-Bố trí mà tôi đã trả về từ bộ điều khiển WebAPI bằng WebClient?Lấy tham số Nội dung-Bố trí
khiển WebAPI
[Route("api/mycontroller/GetFile/{fileId}")]
public HttpResponseMessage GetFile(int fileId)
{
try
{
var file = GetSomeFile(fileId)
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(file));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = file.FileOriginalName;
/********* Parameter *************/
response.Content.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("MyParameter", "MyValue"));
return response;
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
Khách hàng
void DownloadFile()
{
WebClient wc = new WebClient();
wc.DownloadDataCompleted += wc_DownloadDataCompleted;
wc.DownloadDataAsync(new Uri("api/mycontroller/GetFile/18"));
}
void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
WebClient wc=sender as WebClient;
// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
string fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", ""); //FileName ok
/****** How do I get "MyParameter"? **********/
}
var data = e.Result; //File OK
}
Tôi đang trở về một tập tin từ bộ điều khiển WebAPI, tôi gắn tên tập tin trong tiêu đề nội dung trả lời, nhưng tôi cũng muốn để trả về giá trị quảng cáo.
Trong ứng dụng khách, tôi có thể lấy tên tệp, nhưng làm cách nào để nhận thông số quảng cáo?
Tuyệt vời, tôi sẽ đánh dấu đó là câu trả lời đúng, bạn đã viết lớp từ đầu chưa? nếu không, vui lòng cho biết nguồn. – Tuco
Vâng tôi đã làm, nhưng như tôi đã đề cập, nó có thể cần cải tiến hơn nữa, nhưng tôi hy vọng nó giải quyết vấn đề của bạn. –