AngularJS performs an OPTIONS HTTP request for a cross-origin resource

后端 未结 14 1366
生来不讨喜
生来不讨喜 2020-11-22 03:04

I\'m trying to setup AngularJS to communicate with a cross-origin resource where the asset host which delivers my template files is on a different domain and therefore the X

14条回答
  •  逝去的感伤
    2020-11-22 03:12

    Here is the way I fixed this issue on ASP.NET

    • First, you should add the nuget package Microsoft.AspNet.WebApi.Cors

    • Then modify the file App_Start\WebApiConfig.cs

      public static class WebApiConfig    
      {
         public static void Register(HttpConfiguration config)
         {
            config.EnableCors();
      
            ...
         }    
      }
      
    • Add this attribute on your controller class

      [EnableCors(origins: "*", headers: "*", methods: "*")]
      public class MyController : ApiController
      {  
          [AcceptVerbs("POST")]
          public IHttpActionResult Post([FromBody]YourDataType data)
          {
               ...
               return Ok(result);
          }
      }
      
    • I was able to send json to the action by this way

      $http({
              method: 'POST',
              data: JSON.stringify(data),
              url: 'actionurl',
              headers: {
                  'Content-Type': 'application/json; charset=UTF-8'
              }
          }).then(...)
      

    Reference : Enabling Cross-Origin Requests in ASP.NET Web API 2

提交回复
热议问题