【发布时间】:2017-11-06 05:23:23
【问题描述】:
我正在开发一个 .net core web api 项目,这个块让我做噩梦。我正在尝试将请求从 ionic-angular 发送到 .net 核心项目。 GET 请求运行良好。但 POST 请求不是。当我尝试在 chrome 中测试项目时,它对 OPTIONS 请求说 net::ERR_CONNECTION_RESET。我了解 Chrome 在我真正的 POST 请求之前发送预检 OPTIONS 请求。但这就是问题所在。我尝试使用这样的中间件处理该 OPTIONS 请求
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
namespace A.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[] { "http://localhost:8100" });
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");
}
else
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:8100" });
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
}
}
}
public static class OptionsMiddlewareExtensions
{
public static IApplicationBuilder UseOptions(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
}
但它仍然没有帮助。如果有什么技巧,请赐教!
【问题讨论】:
-
托管网页的网址是什么?您尝试发布到的 URL 是什么?
标签: c# google-chrome ionic-framework asp.net-core-2.0