Do I need to enable Cross-Origin Requests for ASP.NET Web API?

0

I did a test application, where I point to a web api that is online, the address of this api works and return the data if it is posted in the browser URL, it does a GET. In the test application I have:

<Div>
    <Select id="method">
        <Option value="get"> GET </option>
        <Option value="post"> POST </option>
        <Option value="put"> PUT </option>
    </Select>
         
    <Input type="button" value="Experimente" onclick="sendRequest()" />
    <Span id='value1'>(Resultado)</span>
 
</Div>
 

@section scripts {
    <script>
    // TODO: Replace with the URL of your WebService app
        var serviceUrl = ‘enderecoapi';
 
    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>
}

You are not returning the data to me, I inspected the data and did not return an error, just "XHR finished loading: GET"

    
asked by anonymous 27.12.2016 / 20:25

1 answer

1

Hello, If the API is in a different domain than the application, you will need to enable cross origin (CORS) in the API.

For example: If you have the application you are at: domain.com , And the domain.com/api api you will not need cross origin

Now if the application is in: mydomain.com , And the otherdomain.com , you must enable cross origin.

I do not know .net, but I imagine this link is useful:

link

More specifically this part:

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

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

and this:

using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

In the origins parameter you should enter the address of the application you want to call api. For tests you can put "*", but do not send to production

Hugs!

    
28.12.2016 / 14:11