gpt4 book ai didi

c# - 获取 Content-Disposition 参数

转载 作者:可可西里 更新时间:2023-11-01 07:50:00 24 4
gpt4 key购买 nike

如何使用 WebClient 获取从 WebAPI Controller 返回的 Content-Disposition 参数?

WebAPI Controller

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

}

客户端

    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
}

我正在从 WebApi Controller 返回一个文件,我在响应内容 header 中附加了文件名,但我还想返回一个附加值。

在客户端中我可以获取文件名,但是我如何获取附加参数?

最佳答案

如果您使用的是 .NET 4.5 或更高版本,请考虑使用 System.Net.Mime.ContentDisposition类:

string cpString = wc.ResponseHeaders["Content-Disposition"];
ContentDisposition contentDisposition = new ContentDisposition(cpString);
string filename = contentDisposition.FileName;
StringDictionary parameters = contentDisposition.Parameters;
// You have got parameters now

编辑:

否则,您需要根据 specification 解析 Content-Disposition header .

这是一个执行解析的简单类,接近规范:

class ContentDisposition {
private static readonly Regex regex = new Regex(
"^([^;]+);(?:\\s*([^=]+)=((?<q>\"?)[^\"]*\\k<q>);?)*$",
RegexOptions.Compiled
);

private readonly string fileName;
private readonly StringDictionary parameters;
private readonly string type;

public ContentDisposition(string s) {
if (string.IsNullOrEmpty(s)) {
throw new ArgumentNullException("s");
}
Match match = regex.Match(s);
if (!match.Success) {
throw new FormatException("input is not a valid content-disposition string.");
}
var typeGroup = match.Groups[1];
var nameGroup = match.Groups[2];
var valueGroup = match.Groups[3];

int groupCount = match.Groups.Count;
int paramCount = nameGroup.Captures.Count;

this.type = typeGroup.Value;
this.parameters = new StringDictionary();

for (int i = 0; i < paramCount; i++ ) {
string name = nameGroup.Captures[i].Value;
string value = valueGroup.Captures[i].Value;

if (name.Equals("filename", StringComparison.InvariantCultureIgnoreCase)) {
this.fileName = value;
}
else {
this.parameters.Add(name, value);
}
}
}
public string FileName {
get {
return this.fileName;
}
}
public StringDictionary Parameters {
get {
return this.parameters;
}
}
public string Type {
get {
return this.type;
}
}
}

那么你可以这样使用它:

static void Main() {        
string text = "attachment; filename=\"fname.ext\"; param1=\"A\"; param2=\"A\";";

var cp = new ContentDisposition(text);
Console.WriteLine("FileName:" + cp.FileName);
foreach (DictionaryEntry param in cp.Parameters) {
Console.WriteLine("{0} = {1}", param.Key, param.Value);
}
}
// Output:
// FileName:"fname.ext"
// param1 = "A"
// param2 = "A"

使用此类时唯一应该考虑的是它不处理没有双引号的参数(或文件名)。

编辑 2:

它现在可以处理不带引号的文件名。

关于c# - 获取 Content-Disposition 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30193569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com