2

I trying to do a request to apns server with http2 request but i got this error message :

Only HTTP/1.0 and HTTP/1.1 version requests are currently supported.\r\nParameter name: value

My request :

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";
}

I using .netframework 4.7.2 in asp.net mvc webapi 2 project

I was using pushsharp but it stopped because it is not support http2 yet

Ahmad Alaa
  • 767
  • 9
  • 30

2 Answers2

3

By default HttpClient uses HTTP 1.1 as mentioned in ms doc

you can try, following way to explicitly tell client object to use version 2

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

Alternatively, you can use Nuget Package WinHttpHandler and pass this handler to client object like,

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

You can check the discussion around this here

mabiyan
  • 667
  • 7
  • 25
0

If using asp.net webform then install below package first

WinHttpHandler Nuget Package

and use the below code

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;