Javascript > WebApi Cross-Origin Ayarı| C#

Merhaba, API’leri şimdiye kadar hiç Ajax ile tetiklememiştim.
Öyle bir ihtiyaç oldu ve hata aldım.
Hatanın da detayı yok maalesef.
status 0 dönüyor.

<script>
    function myFunction() {
        var postData = {
            "Key": "string",
            "Value": "string"
        };
        $.ajax({
            url: "https://www.zamkinos.net/Api/Test",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: 'POST',
            data: JSON.stringify(postData), error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }
                console.log(msg);
            },
            success: function (data) {
                console.log(data);
            }
        });
    }
</script>
<input type="button" onclick="myFunction()" value="Click">

Biraz araştırdıktan sonra çözümü buldum:
Package Manage Console’dan aşağıdaki paketi yüklüyoruz:

> Install-Package Microsoft.AspNet.WebApi.Cors

Sonra WebApiConfig.cs’ye şu satırı ekliyoruz:

config.EnableCors();

Sonra da ilgili Controller’ın tepesine de şunu ekliyoruz:

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class LoginController : ApiController
{
.....
}

Selamlar.

Leave a Reply

Your email address will not be published. Required fields are marked *