Error 404 upon sending request to azure backend while sending Azure Push Notifications?

AliRaza.5445AliRaza.5445 PKMember ✭✭✭

Hi Devs,
I am implementing Azure Push Notifications in my xamarin.forms app. I have created a notification hub on azure. Test send works fine on physical iOS device but when it comes to send notification from one device to other registered devices, server returns Error 404 Not found. Below is the code for my backend service that send the code:

``` using Microsoft.Azure.NotificationHubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace PNS_Backend.Controllers
{
    [RoutePrefix("PushNotifications")]
    public class PushNotifController : ApiController
    {
        [HttpPost]
        [Route("")]
        public async Task<IHttpActionResult> SendNotificationAsync([FromBody] string message)
        {
            // Get the settings for the server project.
            HttpConfiguration config = this.Configuration;
            try
            {
                await SendNotification(message, null);
            }
            catch (Exception ex)
            {
                // Write the failure result to the logs.
                config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
                return BadRequest(ex.Message);
            }

            return Ok();
        }


        [HttpPost]
        [Route("{installationid}")]
        public async Task<IHttpActionResult> SendNotificationAsync(string installationId, [FromBody] string message)
        {
            // Get the settings for the server project.
            HttpConfiguration config = this.Configuration;
            try
            {
                await SendNotification(message, installationId);
            }
            catch (Exception ex)
            {
                // Write the failure result to the logs.
                config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
                return BadRequest(ex.Message);
            }

            return Ok();
        }


        async Task<NotificationOutcome> SendNotification(string message, string installationId)
        {
            // Get the settings for the server project.
            HttpConfiguration config = this.Configuration;


            // The name of the Notification Hub from the overview page.
            string notificationHubName = "gopns_hub";
            // Use "DefaultFullSharedAccessSignature" from the portal's Access Policies.
            string notificationHubConnection = "Endpoint=sb://sampleaddress.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=n1wtqS1Phy+xHZ00OZrrPIDoy9YAnYyMpMsKnN5lRX8=";

            // Create a new Notification Hub client.
            var hub = NotificationHubClient.CreateClientFromConnectionString(
                notificationHubConnection,
                notificationHubName,
                // Don't use this in RELEASE builds. The number of devices is limited.
                // If TRUE, the send method will return the devices a message was
                // delivered to.
                enableTestSend: false);

            // Sending the message so that all template registrations that contain "messageParam"
            // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            var templateParams = new Dictionary<string, string>
            {
                ["messageParam"] = message
            };

            // Send the push notification and log the results.

            NotificationOutcome result = null;
            if (string.IsNullOrWhiteSpace(installationId))
            {
                result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
            }
            else
            {
                result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
            }


            // Write the success result to the logs.
            config.Services.GetTraceWriter().Info(result.State.ToString());
            return result;
        }
    }
}``

Also, below is the code for my Xamarin.Forms button that tries to send the message:
```public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
_client.BaseAddress = new Uri(App.MobileServiceUrl);
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.Timeout = TimeSpan.FromSeconds(120);
}

    HttpClient _client = new HttpClient();

    protected override void OnAppearing()
    {
        base.OnAppearing();

        MessagingCenter.Subscribe<object, string>(this, App.NotificationReceivedKey, OnMessageReceived);
        btnSend.Clicked += OnBtnSendClicked;
    }

    void OnMessageReceived(object sender, string msg)
    {
        Device.BeginInvokeOnMainThread(() => {
            lblMsg.Text = msg;
        });
    }

    async void OnBtnSendClicked(object sender, EventArgs e)
    {
        Debug.WriteLine($"Sending message: " + txtMsg.Text);

        var content = new StringContent("\"" + txtMsg.Text + "\"", Encoding.UTF8, "application/json");
        var result = await _client.PostAsync("PushNotifications", content); // At this line, I get Error 404 as a result and message is not sent.
        Debug.WriteLine("Send result: " + result.IsSuccessStatusCode);
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        MessagingCenter.Unsubscribe<object>(this, App.NotificationReceivedKey);
    }
}```

This line : var result = await _client.PostAsync("PushNotifications", content);
gives me the Error 404 when i call PostAsync on client object.
Can you guys check it and suggest some solutions?
Thanks

Answers

  • Cdn_EuroCdn_Euro Member ✭✭✭
    edited July 2018

    @AliRaza.5445 Same with me, I have the same problem. Did you fix the problem?

  • ashrithaashritha Member ✭✭

    Any updates on this issue? @Cdn_Euro I saw on another thread that you got it working. Can you please let me know how you resolved this exception?

Sign In or Register to comment.