Error trying to consume WebAPI service

3

Since this morning I try to get a JSON that a WebAPI makes available. First I tried with insira o código aqui AngularJS and it was not evolving, so I went to the classic Jquery/Ajax and even then I did not succeed. In my WebAPI , I saw NuGet , I installed CORS , because the reason is to make it work with Cross-Domain . I made a simple example, using CROSS-DOMAIN and it worked fine. What happens is that the project I have here in the company is not working, that is, I can not get the JSON on my client. The service is working well. Well, I'll post the codes and if the question is still unclear, please feel free to ask / ask. Below is the JSON caught in the 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 is 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 to not use Angular, I commented on the call to Angular and did this Javascript, which I put 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 error that gives me the moment I try to consume the service:

  

XMLHttpRequest can not load    link .   In 'Access-Control-Allow-Origin' header is present on the requested   resource. Origin ' link ' is therefore not allowed   access. The response had HTTP status code 500.

The AngularJS is working, because the AngularJS Controller displays the error message on the page that comes from the Service, it is being displayed. The problem is in the serialization (JSON), that is, I can not get the service 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);
    }

Does this method have to configure the Header to prevent the error?

    
asked by anonymous 06.07.2016 / 20:26

1 answer

0

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

<system.webServer>

    <httpProtocol>
       <customHeaders>
       <clear />
       <add name="Access-Control-Allow-Origin" value="*" />
       </customHeaders>
    </httpProtocol> 
.......
    
12.07.2016 / 14:27