Doubt with Enablecors Asp.net web.api

Asked

Viewed 99 times

1

When is the release of an address made using the Enablecors can be used the Route or is it necessary to change something? is correct this way?

[HttpGet]
[Route("consulta/BuscaTipoPagamento")]
[EnableCors(origins: "http://localhost:50907", headers: "*", methods: "*")]
public HttpResponseMessage BuscaTipoPagamento()
{
       try
          {
              var tTabela = new TipoPagamentoAplicacao();
              var listar = tTabela.ListaTodos();
              return Request.CreateResponse(HttpStatusCode.OK, 
                    new { pagamento = listar.ToArray() });
          }
          catch (Exception ex)
          {
             return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
          }
}

1 answer

0


The statement is correct. Whereas you have the Install-Package Microsoft.AspNet.Webapi.Cors package from Nuget installed:

Register in your config

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {                
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Enable CORS in action, controller or global (for all controllers), in your case for one action only.

public class ItemsController : ApiController
{
    public HttpResponseMessage GetAll() { }
    [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
    public HttpResponseMessage GetItem(int id) {  }
    public HttpResponseMessage Post() { ... }
    public HttpResponseMessage PutItem(int id) {  }
}

https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Browser other questions tagged

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