AJBM Posted January 9, 2016 at 11:22 AM Report #591690 Posted January 9, 2016 at 11:22 AM Boas! Eu quero fazer um pedido a uma Web API, mas não estou a conseguir. O pedido chega a Web API mas não retorna os dados. Se eu escrever o endereço diretamente no browser retorna dados, se for pelo javascript dá erro. public class ClientController : ApiController { // GET: api/Client public IEnumerable<string> Get() { return new string[] {"Teste1","Teste2"}; } .... (function () { var app = angular.module("mainApp", []).controller("ClientController", function ($scope, $http) { $scope.Clients = ["Ricardo","Maria"]; $http({ method: 'GET', url: 'http://localhost:60525/api/Client/' }).then(function successCallback(response) { // this callback will be called asynchronously // when the response is available $scope.Clients = response.data; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. alert("Erro: " + response); }); $scope.Title = "Titulo"; }); })();
KTachyon Posted January 9, 2016 at 08:54 PM Report #591729 Posted January 9, 2016 at 08:54 PM Coloca um console.log(response) na função successCallback e confirma se os dados chegam ou não. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
AJBM Posted January 9, 2016 at 09:05 PM Author Report #591732 Posted January 9, 2016 at 09:05 PM Coloca um console.log(response) na função successCallback e confirma se os dados chegam ou não. Os dados não chegam, o alert da função errorCallback é executado.
KTachyon Posted January 9, 2016 at 09:21 PM Report #591734 Posted January 9, 2016 at 09:21 PM Então, se o alert é executado é porque a API devolveu um código de erro. O que aparece na response? Deves lá ter um statusCode. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
AJBM Posted January 9, 2016 at 09:30 PM Author Report #591736 Posted January 9, 2016 at 09:30 PM Resultado: config: Object data: null headers: (d) status: -1 statusText: "" __proto__: Object
KTachyon Posted January 9, 2016 at 09:35 PM Report #591737 Posted January 9, 2016 at 09:35 PM De certeza que o pedido feito pelo javascript chega à API? No browser também acedes ao localhost:60525? “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
AJBM Posted January 9, 2016 at 09:41 PM Author Report #591738 Posted January 9, 2016 at 09:41 PM De certeza que o pedido feito pelo javascript chega à API? Eu defini um breakpoint e quando quando carrego a janela ele para no breakpoint. No browser também acedes ao localhost:60525? Sim. Eu tenho a minha solução com dois projetos: Web API, Angular. Poderá ser isso?
Solution KTachyon Posted January 9, 2016 at 09:56 PM Solution Report #591740 Posted January 9, 2016 at 09:56 PM (edited) Não sei o que queres dizer com isso. O mais provável é o teu browser estar a bloquear pedidos cross-domain. Isto se a tua API e o teu frontend estiverem em domínios diferentes. E, mesmo sendo ambos localhost, se tiverem portos diferentes, o domínio é diferente. Basicamente, o teu browser vai enviar um OPTIONS antes de enviar o GET à API. Se a API não devolver o domínio do frontend no header Access-Control-Allow-Origin (entre outros headers, como o Access-Control-Allow-Methods), o browser não vai tentar fazer o pedido à GET à API. Se quiseres saber mais sobre o assunto procura por CORS. Edited January 9, 2016 at 09:56 PM by KTachyon “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
AJBM Posted January 11, 2016 at 06:44 PM Author Report #591829 Posted January 11, 2016 at 06:44 PM Já funciona. Obrigado 👍 Coloquei isto no web.config <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*"/> </customHeaders> </httpProtocol> ...
KTachyon Posted January 11, 2016 at 11:00 PM Report #591839 Posted January 11, 2016 at 11:00 PM Só um detalhe. O Access-Control-Allow-Origin:* não funciona em todos os browsers. Há browsers que querem mesmo que o servidor especifique eu o domínio autorizado é mesmo aquele em que está. Já tive que resolver este problema e o ideal é tu apanhares o pedido, capturares a origin e devolveres nesse header. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare
AJBM Posted January 15, 2016 at 06:15 PM Author Report #592042 Posted January 15, 2016 at 06:15 PM Eu apanho o pedido, mas o pedido não têm a propriedade Origin public class AllowCORS : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null) { base.OnActionExecuted(actionExecutedContext); //Origin??? actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); } } } public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.JsonFormatter.Indent = true; config.EnableCors(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now