none
asp.net webapi ve cordova RRS feed

  • Soru

  • farklı domainlerde bulunan biri webapi diğeri apache cordova projesinde ajax ile post işlemi gerçekleştirmeye çalışıyorum. fakat hatalardan bi türlü kurtulamadım.

    webapi 

            [System.Web.Http.HttpPost]
            public void Add(string plakaNo)
            {
                Arac arac = new Arac();
                arac.PlakaNo = plakaNo;
                aracManager.Add(arac);
            }

    webapi.config

            public static void Register(HttpConfiguration config)
            {
                // Web API yapılandırması ve hizmetleri
                var cors = new EnableCorsAttribute("http://localhost:4401", "*", "*");
                config.EnableCors(cors);
                // Web API yolları
                config.MapHttpAttributeRoutes();
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        

    corshandler.cs

        public class CorsHandler : DelegatingHandler
        {
            const string Origin = "Origin";
    
            const string AccessControlRequestMethod = "Access-Control-Request-Method";
    
            const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
    
            const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
    
            const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
    
            const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
    
    
    
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                bool isCorsRequest = request.Headers.Contains(Origin);
    
                bool isPreflightRequest = request.Method == HttpMethod.Options;
    
                if (isCorsRequest)
                {
                    if (isPreflightRequest)
                    {
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
    
    
                        string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
    
                        if (accessControlRequestMethod != null)
                        {
                            response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                        }
    
    
    
                        string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
    
                        if (!string.IsNullOrEmpty(requestedHeaders))
    
                        {
    
                            response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
    
                        }
    
    
    
                        TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
    
                        tcs.SetResult(response);
    
                        return tcs.Task;
    
                    }
    
                    else
    
                    {
    
                        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
    
                        {
    
                            HttpResponseMessage resp = t.Result;
    
                            resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
    
                            return resp;
    
                        });
    
                    }
    
                }
    
                else
    
                {
    
                    return base.SendAsync(request, cancellationToken);
    
                }
    
            }
    
        }

    global.asax.cs

            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
    
            }
            protected void Application_BeginRequest()
            {
                if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
                {
                    Response.Flush();
                }
            }


    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" />
            <add name="Access-Control-Allow-Credentials" value="true" />
          </customHeaders>
        </httpProtocol>
        <handlers>
          <remove name="WebDAV" />  
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" /><remove name="OPTIONSVerbHandler" /><remove name="TRACEVerbHandler" /><add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers>
          <validation validateIntegratedModeConfiguration="false"/>
        <modules runAllManagedModulesForAllRequests="true">
          <remove name="TelemetryCorrelationHttpModule" />
          <remove name="WebDAVModule" />
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
        </modules>
      </system.webServer>


    script

        <script>
            $(document).ready(function () {
                $("#datasubmit").click(function () {
                    var data = $("#data").val();
                    //alert(aracplaka);
                    $.ajax({
                        type: "post",
                        dataType: 'json',  
                        url: "http://10.16.0.22:88/api/arac",
                        data: data,
                        success: alert("başarılı"),
                        error: function () {
                            alert("hata")
                        }
                    })
                });
            });
        </script>


    post isteğinde bulunduğumda aşağıdaki hatayı alıyorum;

    Failed to load resource: the server responded with a status of 500 (Internal Server Error)

    26 Mart 2019 Salı 10:14

Tüm Yanıtlar