Commit 3dba2025 by lizefeng

解决跨域问题

parent 177622b0
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AutoTurnOver.Models
{
public class CorsMiddleware
{
private readonly RequestDelegate next;
public CorsMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
{
context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH");
context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
if (context.Request.Method.Equals("OPTIONS"))
{
context.Response.StatusCode = StatusCodes.Status200OK;
return;
}
}
await next(context);
}
}
}
...@@ -3,6 +3,7 @@ using System.Collections.Generic; ...@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using AutoTurnOver.Common; using AutoTurnOver.Common;
using AutoTurnOver.Models;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
...@@ -89,7 +90,7 @@ namespace AutoTurnOver ...@@ -89,7 +90,7 @@ namespace AutoTurnOver
// Shows UseCors with CorsPolicyBuilder. // Shows UseCors with CorsPolicyBuilder.
//app.UseCors("AllowSpecificOrigin"); //app.UseCors("AllowSpecificOrigin");
app.UseMiddleware<CorsMiddleware>();
app.UseStaticHttpContext(); app.UseStaticHttpContext();
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment