2017-05-15 20 views
1

2つのCORSポリシーを設定しようとしています。 1つはAPIのデフォルトとして使用され、もう1つはControllersに必要なものとして使用されます。私がこれをやりたいのは、電子メール情報を持つオブジェクトを取り込み、電子メールを送信して(自分のWebページの連絡先ボックスと一緒に使用する)、自分のドメインからの要求のみを受け入れるエンドポイントがあるからです。ASP .NETコアで複数のCORSポリシーを使用する

マイstartup.csファイルの抜粋:

public void ConfigureServices(IServiceCollection services) 
     { 
      services.AddCors(options => 
      { 
       options.AddPolicy("Example", 
        builder => builder.WithOrigins("http://www.example.com")); 
       options.AddPolicy("AllowAll", 
        builder => builder.AllowAnyOrigin()); 
      }); 

      services.AddMvc(); 
      //other configure stuff 
     } 


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     app.UseCors(builder => 
     { 
      builder.AllowAnyHeader(); 
      builder.AllowAnyMethod(); 
      builder.WithOrigins("AllowAll"); 
     }); 

     app.UseMvcWithDefaultRoute(); 
    } 

マイemailcontroller.csファイル:

using System.Threading.Tasks; 
using MyAPI.Models; 
using MyAPI.Services; 
using Microsoft.AspNetCore.Cors; 
using Microsoft.AspNetCore.Mvc; 

namespace MyAPI.Controllers 
{ 
    [Produces("application/json")] 
    [Route("api/Email")] 
    [EnableCors("Example")] 
    public class EmailController : Controller 
    { 
     private readonly IEmailSender _emailSender; 

     public EmailController(IEmailSender emailSender) 
     { 
      _emailSender = emailSender; 
     } 

     [HttpPost] 
     public async Task Post([FromBody] Email email) 
     { 
      await _emailSender.SendEmailAsync(email); 
     } 
    } 

} 

Javascriptが電子メールを送信するために使用:

function sendEmail(email) 
{ 
    var urlToApi = "http://<ipToApi>:5000/api"; 
    $.ajax({ 
      method: "POST", 
      contentType: "application/json; charset=utf-8", 
      data: JSON.stringify(email),  
      url: urlToApi + "/email/", 
      success: function(data) { 
       console.log(data); 
       console.log('probably sent'); 
      }, 
      error: function(jqXHR, textStatus, errorThrown){ 
       console.log(textStatus); 
       alert("There was like, an error doing that"); 
      } 
     }); 
} 

これは私がhttp://www.example.comから送信しようとして得るものです

XMLHttpRequest cannot load http://<ipToApi>:5000/api/email/. 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://www.example.com' is therefore not allowed access. 

EDIT

これは動作します:

services.AddCors(options => 
      { 
       options.AddPolicy("Example", 
        builder => builder.WithOrigins("http://www.example.com") 
             .AllowAnyHeader() 
             .AllowAnyMethod()); 
       options.AddPolicy("AllowAll", 
        builder => builder.AllowAnyOrigin() 
             .AllowAnyHeader() 
             .AllowAnyMethod()); 
      }); 
+1

"AllowAll"としてオリジンを設定しています – Mardoxx

+0

@Mardoxx私はそれがデフォルトを設定すると思っていました。私がすべてコメントしたら、私はすべてのコントローラで[EnableCors( "mypolicy")]を使うことができますか? – Jrow

+1

あなたは 'app.UseCors(" AllowAll ");'を使うべきです – Mardoxx

答えて

3

デフォルトCORSポリシーの使用にapp.UseCors(string policyName)過負荷を設定します。

すべてのヘッダーとメソッドを拒否しているため、CORS要求が失敗します。私が読んだところから、CORS仕様では、チェックのいずれかが失敗した場合、ヘッダーを設定しないでください。実装hereを参照してください。Originのチェックに合格したにもかかわらず、お客様のクライアントに標準No 'Access-Control-Allow-Origin' header is presentというエラーが表示される可能性が最も高いです。というヘッダーがまったく追加されています。

次のコードは期待どおりに動作するはずです。[EnableCors(...)]デコレータはデフォルトを上書きする必要があります。

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddCors(options => 
    { 
     options.AddPolicy("Example", 
      builder => builder.WithOrigins("http://www.example.com") 
           .AllowAnyHeader() 
           .AllowAnyMethod()); 
     options.AddPolicy("AllowAll", 
      builder => builder.AllowAnyOrigin() 
           .AllowAnyHeader() 
           .AllowAnyMethod()); 
    }); 

    services.AddMvc(); 
    //other configure stuff 
} 


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    app.UseCors("AllowAll"); //Default 

    app.UseMvcWithDefaultRoute(); 
} 

お客様のポリシーに.AllowCredentials()を追加する必要がありますが、わかりません。おそらくhereをお読みください?

関連する問題