🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / C# RMOS / web api 2 ajax cors hatası giderme Enable Enabling CORS

1-) C# RMOS - web api 2 ajax cors hatası giderme Enable Enabling CORS

 

27.03.2025 TARİHİNDE BULDUĞUM KESİN ÇÖZÜM

 

1. OptionsVerbHandler.cs aşağıdaki kod olmazsa yorum satırlarını aç

 

using System.Net;

using System.Net.Http;

using System.Threading;

using System.Threading.Tasks;

 

namespace PosPrinter.App_Start

{

    public class OptionsVerbHandler : DelegatingHandler

    {

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

        {

            // Eğer gelen istek OPTIONS ise : olmazsa yorum satırlarını aç

            if (request.Method == HttpMethod.Options)

            {

                var response = new HttpResponseMessage(HttpStatusCode.OK);

                //response.Headers.Add("Access-Control-Allow-Origin", "*");

                //response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

                //response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");

                return Task.FromResult(response);

            }

 

            return base.SendAsync(request, cancellationToken);

        }

    }

}

 

 

2. WebApiConfig.cs

 

 config.MessageHandlers.Add(new OptionsVerbHandler()); // <- add this line

 

 config.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{id}",

                defaults: new { id = RouteParameter.Optional }

 );

 

 

 

DİĞERLERİNE BAKMASANDA OLUR

 

kaynak : https://www.linkedin.com/learning/advanced-asp-dot-net-web-api-2-2/enabling-cors

kaynak : https://stackoverflow.com/questions/27504256/mvc-web-api-no-access-control-allow-origin-header-is-present-on-the-requested

kaynak : https://medium.com/@vbgurcan/asp-net-core-webapi-access-control-allow-origin-cors-hatas%C4%B1-ve-%C3%A7%C3%B6z%C3%BCm%C3%BC-df19b2817017

 

 

 

1. Adım nuget console : https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors

 

Install-Package Microsoft.AspNet.WebApi.Cors

 

2. Adım -> App_Start -> WebApiConfig.cs

 

 public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)

        {

 

            config.EnableCors();

 

3. Adım Controller.cs

 

using System.Web.Http.Cors;

 

namespace YaziciApi2.Controllers

{

 

    [EnableCors("*","*","*")]

    public class PrinterController : ApiController

 

 

 

DİĞER

 

You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config

<system.webServer>

  <httpProtocol>

    <customHeaders>

      <add name="Access-Control-Allow-Origin" value="*" />

      <add name="Access-Control-Allow-Headers" value="Content-Type" />

      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />

    </customHeaders>

  </httpProtocol>

</system.webServer>

 

 

 

AJAX İLE İSTEK

 

 

function afficheorga(a){

$.ajax({

url: "https://cubber.zendesk.com/api/ organizations.json",

type: 'GET',

dataType: 'jsonp',

CORS: true ,

contentType:'application/json',

secure: true,

headers: {

'Access-Control-Allow-Origin': '*',

},

beforeSend: function (xhr) {

xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));

},

success: function (data){

console.log(data.organizations[0].name);

var organisation = data.organizations[0].name;

$("#company").text(organisation);

}

}) }

 

 

 

ornek 2

 

 

<!DOCTYPE html>

<html>

<head>

<script src = "https://ajax.googleapis.com/ajax/libs/jQuery/3.3.1/jQuery.min.js"></script>

<script>

var settings = {

'cache': false,

'dataType': "jsonp",

"async": true,

"crossDomain": true,

"url": "https://maps.googleapis.com/maps/api/distancematrix/json?units ",

"method": "GET",

"headers": {

"accept": "application/json",

"Access-Control-Allow-Origin":"*"

}

}

$.ajax(settings).done(function (response) {

console.log(response);

});

</script>

</head>

<body>

<p id="pid">JQuery ajax Code executed successfully.</p>

</body>

</html>

 

 

 

eğer f12 deki curl de options a cors hatası veriyorsa post isteği haricinde options isteğini de koy ve ok dön

 

[HttpOptions]

        [Route("api/Recete/ReceteGetir")]

        public HttpResponseMessage Options()

        {

            var response = new HttpResponseMessage(HttpStatusCode.OK);

            return response;

        }

 

 

 

 

 

 

 2025 Mart 27 Perşembe
 534