Error while trying to consume Webapi service

Asked

Viewed 334 times

4

since this morning I try to catch a JSON that a WebAPI available. I first tried with insira o código aquiAngularjs and was not evolving, so I went to the classic Jquery/Ajax and yet I did not succeed. In my WebAPI i, saw NuGet, installed the CORS, because the reason is to make it work with Cross-Domain. I made a simple example using CROSS-DOMAIN and it worked well. What happens is that the project that I have here at the company is that it’s not working, I mean, I can’t get the JSON on my client. The service is working fine. Well, I’ll post the codes and in case the question is still unclear, please feel free to ask/question. Below is the JSON captured in Browser. Note, that by ajax, I do not have a date (that’s what I understood), but rather a data.items.

{
  "totalRecords": 40,
  "pagination": {
    "pageIndex": 1,
    "pageSize": 40,
    "lastPage": 1
  },
  "sort": {
    "fields": "Nome",
    "directions": "ASC"
  },
  "items": [
    {
      "id": 49,
      "nome": "Assinatura PME",
      "tipoContato": {
        "codigo": "T",
        "descricao": "Texto"
      },
      "dataUltimaAtualizacao": "2015-06-11T22:13:52",
      "loginUltimaAtualizacao": "Teste"
    },
    {
      "id": 14,
      "nome": "Capa para Baixo - Cartas",
      "tipoContato": {
        "codigo": "T",
        "descricao": "Texto"
      },
      "dataUltimaAtualizacao": null,
      "loginUltimaAtualizacao": null
    }
  ]
}

This is the service code (Apicontroller):

using System.Web.Http.Cors;
namespace X.EstruturaOrganizacional.Api.Controllers
{
    [RoutePrefix("api/estruturaOrganizacional")]
    [EnableCors(origins: "http://localhost:64628/", headers: "*", methods: "*")]
    public class TipoContatoOperadoraController : ApiXController
    {
        private readonly ITipoContatoOperadoraService service;

        public TipoContatoOperadoraController()
        {
            DependencyResolver.Resolve(Container);

            service = Container.Resolve<ITipoContatoOperadoraService>();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && service != null)
            {
                service.Dispose();
            }

            base.Dispose(disposing);
        }

        [HttpGet]
        [Route("tiposContatoOperadora")]
        //[CleanOutCompression]
        [CacheOutput(ClientTimeSpan = 10, ServerTimeSpan = 10)]
        public Task<HttpResponseMessage> ObterTiposContatoOperadora(
            string sortFields = "Nome",
            string sortDirections = "ASC",
            int? pageSize = null,
            int pageIndex = 1)
        {
            IEnumerable<TipoContatoOperadora> lista = service.Listar(
                sortFields,
                sortDirections,
                pageSize,
                pageIndex,
                out recordCount,
                out sorts);

            return CreateResponseForList(lista.ToListModel(), pageIndex, pageSize);
        }

        [HttpGet]
        [Route("tiposContatoOperadora/{id}")]
        //[CleanOutCompression]
        [CacheOutput(ClientTimeSpan = 10, ServerTimeSpan = 10)]
        public Task<HttpResponseMessage> ObterTipoContatoOperadoraPorId(
            byte id)
        {
            TipoContatoOperadora item = service.ConsultarPorCodigo(id);

            return CreateResponseForItem(item.ToModel());
        }
    }
}

And here’s my client(Angular)

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Tipo Contato Operadora</h2>

<div data-ng-controller="TipoContatoOperadoraController">
    <div class="panel panel-default">
        <div class="panel-heading">Lista de Tipo de Contato das Operadoras</div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12">
                        <strong>{{erro}}</strong>
                    </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <tr>
                                    <th>Cod. Tipo Contato</th>
                                    <th>Nome Tipo Contato</th>
                                    <th>Ind. Tipo Contato</th>
                                    <th>Data Atualização</th>
                                    <th>Cod. Usuário</th>
                                </tr>
                                <tr data-ng-repeat="lista in listaTipoContatoOperadora">
                                    <td>{{ lista.id }}</td>
                                    <td>{{ lista.nome }}</td>
                                    <td>{{ lista.tipoContato }}</td>
                                    <td>{{ lista.dataUltimaAtualizacao }}</td>
                                    <td>{{ lista.loginUltimaAtualizacao }}</td>
                                </tr>
                            </table>
                        </div>
                    <input type="button" value="Tente Isso" onclick="sendRequest()" />
                    <span id='value1'>(Result)</span>
                </div>
            </div>
        </div>
    </div>
</div>

My Angular controller:

var app = angular.module('app', []);

//app.controller('TipoContatoOperadoraController', ['$scope', '$http', TipoContatoOperadoraController]);

app.controller('TipoContatoOperadoraController', function ($scope, $http) {

    $http.get('http://localhost:7215/api/estruturaOrganizacional/tiposContatoOperadora')
    .success(function (data) {

        $scope.listaTipoContatoOperadora = data.items;
    })
    .error(function () {
        $scope.erro = 'Erro: Não foi possível carregar a lista do tipo de contato das operadoras.';
    });
})

In an attempt not to use Angular, I commented every call to Angular and made this Javascript, which I placed below in my Index:

@section scripts {
    <script>
    // TODO: Replace with the URL of your WebService app
        var serviceUrl = 'http://localhost:7215/api/estruturaOrganizacional/tiposContatoOperadora';

    function sendRequest() {
        var method = $('#method').val();

        $.ajax({
            type: method,
            url: serviceUrl
        }).done(function (data) {
            $('#value1').text(data);
        }).error(function (jqXHR, textStatus, errorThrown) {
            $('#value1').text(jqXHR.responseText || textStatus);
        });
    }
    </script>
}

This is the mistake that comes at the moment when I try to consume the service:

Xmlhttprequest cannot load http://localhost:7215/api/structureOrganization/typesContactOperator. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:64628' is therefore not allowed access. The Response had HTTP status code 500.

The button Try That and the span, I used it with pure javascript for testing, without the Angular table.

Angularjs is working as the Angularjs Controller displays the Cerror message on the page coming from the Service, is being displayed. The real problem is serialization (JSON), that is, I can’t get the service’s JSON(Function(data)).

Within my Webapi controller, I have this method:

[HttpGet]
[Route("tiposContatoOperadora")]
//[CleanOutCompression]
[CacheOutput(ClientTimeSpan = 10, ServerTimeSpan = 10)]
public Task<HttpResponseMessage> ObterTiposContatoOperadora(
      string sortFields = "Nome",
      string sortDirections = "ASC",
      int? pageSize = null,
      int pageIndex = 1)
    {
       IEnumerable<TipoContatoOperadora> lista = service.Listar(
         sortFields,
         sortDirections,
         pageSize,
         pageIndex,
         out recordCount,
         out sorts);

         return CreateResponseForList(lista.ToListModel(), pageIndex, pageSize);
    }

Could it be that in this method I have to configure Header to prevent the error?

  • http://answall.com/a/134917/3999

  • @Laerte, I don’t see as duplicate. My question has to do with Webapi and Angularjs and in this link the title is this: Como obter as informações de meta tag de uma url externa?

  • You want to disable the Cors or use it?

  • 1

    @Diegoaugusto, use, because it is Cross-Domain, and with CORS it is easier, but I think the problem is not there. And the service I am not aware of. The date variable inside the controller, comes as Undefined and I can display the Angulajs error message, so I assume the problem lies in the way JSON is. In Postman I can capture JSON and in the idem browser, but not in my client.

  • Cara n got it very well, but since you are using CORS you should not pass a header to the back-end?

  • http://stackoverflow.com/questions/24461605/angularjs-and-owin-authentication-on-webapi

  • So, I have the impression that the request in the angular controller is not even working. The weird thing is that in the IE there is no error. It even tries to mount the table with 5 rows (actually it is 40), but nothing inside, no value in the columns. If you are not ordering, the data comes undefined, that is a fact.

Show 3 more comments

1 answer

0

I added these lines to my web.config and solved:

<system.webServer>

    <httpProtocol>
       <customHeaders>
       <clear />
       <add name="Access-Control-Allow-Origin" value="*" />
       </customHeaders>
    </httpProtocol> 
.......
  • If you have decided to put it as answered please so that the question is not open.

Browser other questions tagged

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