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());
});
"AllowAll"としてオリジンを設定しています – Mardoxx
@Mardoxx私はそれがデフォルトを設定すると思っていました。私がすべてコメントしたら、私はすべてのコントローラで[EnableCors( "mypolicy")]を使うことができますか? – Jrow
あなたは 'app.UseCors(" AllowAll ");'を使うべきです – Mardoxx