我没有使用 Flurl,而是尝试使用 HttpClient 实现相同的目标。那没有用,所以我为 Flurl 创建了一个扩展方法。
https://stackoverflow.com/a/44543016/915414建议使用 StringContent 来更改 Content-Type:
var jobInJson = JsonConvert.SerializeObject(job);
var json = new StringContent(jobInJson, Encoding.UTF8);
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=verbose");
var flurClient = GetBaseUrlForOperations("Jobs");
return await flurClient.PostAsync(json).ReceiveJson<Job>();
尽管这确实改变了 Content-Type,但 charset=utf-8 仍然存在。
我反编译了 System.Net.Http.StringContent 以查看它是如何工作的。它默认为一个字符集:
this.Headers.ContentType = new MediaTypeHeaderValue(mediaType == null ? "text/plain" : mediaType)
{
CharSet = encoding == null ? HttpContent.DefaultStringEncoding.WebName : encoding.WebName
};
你猜怎么着...... PostUrlEncodedAsync 的核心是使用 StringContent。
所以,我为 Flurl 创建了一个扩展方法,它使用了类似的 StringContent 实现,其中 CharSet = "";
PostUrlEncodedAsyncWithoutCharset:
public static class HttpExtensions
{
public static Task<HttpResponseMessage> PostUrlEncodedAsyncWithoutCharset(this IFlurlClient client, object data, CancellationToken cancellationToken = default(CancellationToken), HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
CapturedUrlContentCustom urlEncodedContent = new CapturedUrlContentCustom(client.Settings.UrlEncodedSerializer.Serialize(data));
return client.SendAsync(HttpMethod.Post, (HttpContent)urlEncodedContent, new CancellationToken?(cancellationToken), completionOption);
}
}
CapturedUrlContentCustom:
public class CapturedUrlContentCustom : CapturedStringContentCustom
{
public CapturedUrlContentCustom(string data)
: base(data, (Encoding) null, "application/x-www-form-urlencoded")
{
}
}
捕获的字符串内容自定义:
public class CapturedStringContentCustom : CustomStringContent
{
public string Content { get; }
public CapturedStringContentCustom(string content, Encoding encoding = null, string mediaType = null)
: base(content, encoding, mediaType)
{
this.Content = content;
}
}
自定义字符串内容:
public class CustomStringContent : ByteArrayContent
{
private const string defaultMediaType = "application/x-www-form-urlencoded";
public CustomStringContent(string content)
: this(content, (Encoding)null, (string)null)
{
}
public CustomStringContent(string content, Encoding encoding)
: this(content, encoding, (string)null)
{
}
public CustomStringContent(string content, Encoding encoding, string mediaType)
: base(CustomStringContent.GetContentByteArray(content, encoding))
{
this.Headers.ContentType = new MediaTypeHeaderValue(mediaType == null ? "application/x-www-form-urlencoded" : mediaType)
{
CharSet = ""
};
}
private static byte[] GetContentByteArray(string content, Encoding encoding)
{
if (content == null)
throw new ArgumentNullException(nameof(content));
if (encoding == null)
encoding = Encoding.UTF8;
return encoding.GetBytes(content);
}
}
现在,您可以调用 PostUrlEncodedAsyncWithoutCharset 并且不会出现 charset=utf-8 。