Fügen Sie Ihrem Projekt eine Middleware-Klasse hinzu, um das OPTIONS Verb zu behandeln.
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
namespace Web.Middlewares
{
public class OptionsMiddleware
{
private readonly RequestDelegate _next;
private IHostingEnvironment _environment;
public OptionsMiddleware(RequestDelegate next, IHostingEnvironment environment)
{
_next = next;
_environment = environment;
}
public async Task Invoke(HttpContext context)
{
this.BeginInvoke(context);
await this._next.Invoke(context);
}
private async void BeginInvoke(HttpContext context)
{
if (context.Request.Method == "OPTIONS")
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
context.Response.StatusCode = 200;
await context.Response.WriteAsync("OK");
}
}
}
public static class OptionsMiddlewareExtensions
{
public static IApplicationBuilder UseOptions(this IApplicationBuilder builder)
{
return builder.UseMiddleware<OptionsMiddleware>();
}
}
}
Dann füge app.UseOptions();
dies als die erste Zeile in Startup.cs im Verfahren Konfigurieren.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseOptions();
}
Was ist ein spezifisches Szenario, in dem dies nicht gelingt? Wenn es "immer schief geht für irgendeinen Chrome/ff-Browser, der CORS macht", wie wird das nicht schon vom Framework abgedeckt? Scheint so, als wäre das eine ziemlich große Unterlassung. – ssmith
Ich stimme zu. So ist es jedoch. Mit diesem Framework können Sie CORS mit integrierten Funktionen ausführen, es werden jedoch keine OPTIONS-Aufrufe ausgeführt. Dies ist Voraussetzung für die normale Verwendung domänenübergreifender API-Aufrufe von Browsern. Sie können dies jedoch vermeiden, indem Sie einen einfacheren Anruf ausführen, wie zum Beispiel den Typ text/plain und einige andere Dinge. Dann führt der Browser den OPTIONS-Aufruf nicht zuerst aus. –