当前仅支持HTTP/1.0和HTTP/1.1版本请求



我试图用http2请求向apns服务器发出请求,但收到了以下错误消息:

当前仅支持HTTP/1.0和HTTP/1.1版本请求。\\r\n参数名称:值

我的请求:

public static async Task<string> SendManualApns(int type, long? requestId, string title, string message, int badge, string deviceToken)
{
var cert = new X509Certificate2(HttpContext.Current.Server.MapPath(ApnCertPath), ApnCertPassword, X509KeyStorageFlags.MachineKeySet);
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.sandbox.push.apple.com/3/device/" + deviceToken);
req.Version = new Version(2, 0);
req.Headers.Add("apns-topic", cert.Subject.Substring(cert.Subject.LastIndexOf('=') + 1));
string sound = type == (short)NotificationType.RequestTechnicianNow ? "spaceBell.caf" : "default";
string category = type == (short)NotificationType.RequestTechnicianNow ? "nowRequestCategory" : "none";
req.Content = new StringContent("{"aps":{"alert":{"title":"" + title + "","body":"" + message + ""},"badge":" + badge + ","sound":"" + sound + "","requestId":" + requestId + ","type":" + type + ","category":"" + category + ""}}");
var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual };
handler.ClientCertificates.Add(cert);
var response = await new HttpClient(handler).SendAsync(req);
string content = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
return "APNS error " + response.StatusCode + ": " + content;
return "success";
}

我在asp.net mvc webapi 2项目中使用.netframework 4.7.2

我正在使用pushsharp,但它停止了,因为它还不支持http2

默认情况下,HttpClient使用ms doc 中提到的HTTP 1.1

您可以尝试以下方式明确告诉clientobject使用版本2

var client = new HttpClient()
{
BaseAddress = new Uri("https://localhost:5001"),
DefaultRequestVersion = new Version(2, 0)
};

或者,您可以使用Nuget PackageWinHttpHandler并将此handler传递给client对象,如

var handler = new WinHttpHandler();
var client = new HttpClient(handler); 

你可以在这里查看有关的讨论

如果使用asp.net网络表单,请首先安装以下软件包

WinHttpHandler Nuget包

并使用以下代码

var apnSettings = new ApnSettings
{
AppBundleIdentifier = "",
P8PrivateKey = "",
P8PrivateKeyId = "",
TeamId = "",
ServerType = ApnServerType.Development
};
var httpHandler = new WinHttpHandler();
var httpClient = new HttpClient(httpHandler);
var apn = new ApnSender(apnSettings, httpClient);
var payload = new AppleNotification(Guid.NewGuid(), messageBody, "MyNotification");
var apnsResponse = Task.Run(() => apn.SendAsync(payload, deviceId)).Result;

最新更新