是否可以手动预检多个CORS资源?

时间:2016-03-29 20:16:40

标签: ajax cors

因此,this清楚地表明您需要为服务器上的每个资源提供单独的CORS预检请求,因为我正在使用需要自定义标头(以及内容类型JSON)的RESTFul API。但是,我想避免为(几乎)每次请求进行两次往返。

我理想的解决方案是在一个请求中预检多个资源。因此,如果我想允许网络应用发布到/user/media/preferences,我们可以提前在一个请求中执行此操作,甚至在这些请求首次发送之前,否则可怕延迟被添加。这可能与CORS有关吗?

1 个答案:

答案 0 :(得分:0)

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
           //config.SuppressDefaultHostAuthentication();
           //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();
            //var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
           // xml.UseXmlSerializer = true;

            //var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            //json.SerializerSettings.PreserveReferencesHandling =
           // Newtonsoft.Json.PreserveReferencesHandling.All;
            //json.SerializerSettings.DateFormatHandling
            //= Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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

//And on WEBAPI your controller try this.

[EnableCorsAttribute("http://localhost:8080/", "*", "*")]
    public class SampleController : ApiController
    {
        // GET: api/Club

        public IEnumerable<Sample> Get()
        {
            var SampleRepository = new SampleRepository();
            return SampleRepository.Retrieve();
        }

        // GET: api/Sample/id
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/sample
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/sample/id
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/sample/id
        public void Delete(int id)
        {
        }
    }

//In AngularJS you will get what you want this way using CORS through WEB API

(function () {
    "use strict";
    angular
        .module('sampleManagement')
        .controller('SampleListController',
                     ['sampleResource',
                         SampleListController]);

    function SampleListController(sampleResource) {
        var vm = this;

        sampleResource.query(function (data) {
            vm.Sample = data;

        });
    }

}());



(function () {
    "use strict";

    var app = angular.module('sampleManagement',
        ['common.services']);

}());


(function () {
    "use strict";
    angular.module('common.services',
        ['ngResource'])
    .constant('appSettings',
    {
        serverPath: "http://localhost:8080/"
    });
}());



(function () {
    "use strict";
    angular
        .module('common.services')

        .factory('sampleResource',
        ['$resource',
            "appSettings",
        sampleResource])

    function sampleResource($resource, appSettings) {

        return $resource(appSettings.serverPath + "api/Club/:id");

    }
    app.config(['$resourceProvider', function($resourceProvider) {

        $resourceProvider.defaults.stripTrailingSlashes = false;
    }]);
}());