Consuming a WEB API in Visual Studio

1

I've created a WEB API in ASP.NET that is hosted on a web server. This WEB API accesses a table in SQL Server where I have a table called Products with Id, Name, Description and Price, I did the tests via POSTMAN and it is working correctly, but when I try to consume the method to bring a specific product via xamarin application no visual studio

I get the following error message in break mode

application in interrupt mode

Unhandled Exception:

System.Net.Http.HttpRequestException: <Timeout exceeded getting exception details>

Below is my code to bring a specific product accessing the API on the server

public class DataService
{
    public async Task<List<Produto>> GetProductAsync(string NomeProduto)
    {
        using (var client = new HttpClient())
        {

            string url = "http://ProdutosAPI.servidor.com/api";

            try
            {
               var uri = url + "/" + NomeProduto.ToString();
               HttpResponseMessage response = await client.GetAsync(uri);
               var ProdutoJsonString = await response.Content.ReadAsStringAsync();
               var Produto = JsonConvert.DeserializeObject<List<Produto>>(ProdutoJsonString);
               return Produto;

            }
            catch (Exception ex)

            {
                throw ex;
            }

        }

    }

}
    
asked by anonymous 05.07.2018 / 13:35

1 answer

0

Luiz, despite being an API and online, the server blocks requests from outside for security reasons.

In order for it to work in your global.asa file, try this.

private void EnableCrossDmainAjaxCall()
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                // HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }

        }

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetNoStore();
            EnableCrossDmainAjaxCall();
        }

If this does not work, read this: link

    
06.07.2018 / 11:40