Can I access a Web Api from Windows Phone?

Asked

Viewed 75 times

1

I developed an Api that communicates with my database and put it on IIS. Testing in Windows Forms applications, the search of the api data works normally, but when I try to run it inside the Windows Phone app returns the following error:

{System.Net.Webexception: The remote server returned an error: Notfound. ---> System.Net.Webexception: The remote server returned an error: Notfound. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.b__d(Object sendState) at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.b__0(Object sendState) --- End of inner exception stack trace --- at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(Webrequest request, Iasyncresult result) at System.Net.Webclient.Downloadbitsresponsecallback(Iasyncresult result)}

Why is the error occurring? I test the app by the emulator of Visual Studio 2013 itself, will it be necessary to disable some firewall or do some special configuration?

2 answers

0

Are you using localhost? You can’t even test for the emulator. You have to exchange localhost for the host IP.

0

This Notfound error is a much more general error than you think. It may occur when the API does not actually exist, or exists but returns incorrect code status or, what I find most common, when it gives some error due to proxy.

I have apps in the Windowsphone store that consume Webapi. Once Voce is sure that it is not proxy problem, firewall, etc., the code below works perfectly in my application.

Obs:

1 - My app is Windows Phone Silverlight 8.1.

2 - Test your Apps directly on your device whenever possible

try
{
    var webClient = new WebClient();

    // A minha WebApi implementa um DelegatingHandler para autenticação customizada
    // Por isso passo o usuario e senha.
    // Se a sua nao tiver, basta comentar a linha abaixo.
    webClient.Credentials = new NetworkCredential("Usuario", "Senha");

    // Progresso do download do arquivo
    webClient.DownloadProgressChanged += (sender, e) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            // Label com o total de bytes ja baixado. Tipo: 200 de 5000, 300 de 5000, etc...
            lblDownloadStatus.Text = "Baixado " + GetFileSize(e.BytesReceived) + "/" + GetFileSize(e.TotalBytesToReceive);

            // Percentual baixado. Tipo: 5%... 10%... etc...
            lblPercentual.Text = e.ProgressPercentage + "%";
        });
    };

    // Fim do processo de download do arquivo. Agora é só tratar o que voce quiser.
    webClient.OpenReadCompleted += (sender, e) =>
    {
        if (e.Error == null && !e.Cancelled)
        {
            Dispatcher.BeginInvoke(() =>
            {
                Minha_Funcao_Para_Tratar_O_Stream_Baixado(e.Result);
            });
        }
        else
        {
            string erro = e.Error.Message;
            if (erro.ToString().Contains("not found"))
            {
                MessageBox.Show("Não foi possível realizar o download do arquivo. Por favor, verifique as configurações da sua internet e tente novamente.");
            }
            else
            {
                MessageBox.Show("Erro ao baixar arquivo: " + erro);
            }
        }
    };

    // Abre e executa a URL.
    webClient.OpenReadAsync(new Uri("http://www.suaapi.com/DownloadArquivo"));
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.