C# WebSocket握手期间出错:意外响应代码400
我为他准备了网络API和Angular应用程序 我在web api端启用了cors策略:C# WebSocket握手期间出错:意外响应代码400,c#,angular,web,asp.net-core,C#,Angular,Web,Asp.net Core,我为他准备了网络API和Angular应用程序 我在web api端启用了cors策略: services.AddCors(options => { options.AddPolicy("CorsPolicy", b => { b.AllowAnyOrigin() .AllowAnyMe
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", b =>
{
b.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}
);
});
app.UseCors("CorsPolicy");
我从Angular发送get请求,如下所示:
this._httpClient.get(`WebApi link`);
但捕捉错误:
WebSocket握手期间出错:意外响应代码400
我做错了什么
这个链接在《邮递员》中完美地发挥了作用,我得到了结果
Web API使用win-auth
UPD
Web API端在Startup.cs中有此设置:
public class Startup
{
private readonly ILoggerFactory _loggerFactory;
public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory)
{
AutomapperConfig.Init();
_loggerFactory = loggerFactory;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
services.AddMvc();
services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
services.AddAuthorization(options =>
{
foreach (var action in Action.All)
options.AddPolicy(action.Name, policy =>
policy.Requirements.Add(new AssemblyStorageRequirement(action)));
});
services.AddSingleton<IAuthorizationHandler, AssemblyStorageRequirementHandler>();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", b =>
{
b.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}
);
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
services.AddOptions();
services.AddSingleton(Configuration); // IConfigurationRoot
services.AddSingleton<IConfiguration>(Configuration); // IConfiguration explicitly
return services.AddDiConfig(Configuration);
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
/// <param name="appLifetime"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddLog4Net();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseAuthentication();
app.UseResponseCompression();
app.UseCors("CorsPolicy");
app.UseMvc();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
appLifetime.ApplicationStopped.Register(DiConfig.DisposeContainer);
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", b =>
{
b.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}
);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
请求头:获取
wss://localhost:44391/sockjs-node/616/kjiu00aa/websocket HTTP/1.1
主机:localhost:44391连接:升级Pragma:无缓存
缓存控制:无缓存升级:websocket来源:
Sec WebSocket版本:13用户代理:
Mozilla/5.0(Windows NT 6.1;Win64;x64)AppleWebKit/537.36(KHTML,
像Gecko)Chrome/72.0.3626.121 Safari/537.36接受编码:gzip,
deflate,br接受语言:ru-ru,ru;q=0.9,在美国;q=0.8,en;q=0.7
Sec WebSocket键:Ia0VO1G8+d52FJG74UvsQw==Sec WebSocket扩展:
磁通泄气;客户端\u最大\u窗口\u位
响应标题:
HTTP/1.1 400错误请求传输编码:分块变化:来源
服务器:Kestrel访问控制允许凭据:true
访问控制允许来源:X-SourceFiles:
=?UTF-8?B?RTPCUHJVAMVJDHNCVEZTXE9JDG9WDXNTZXJ2AWNLC1XBC3NLBWJSEVN0B3JHZ2VCQXNZW1IBHLTDG9YYWDLV2VIU2L0ZVXBC3NLBWJSEVN0B3JHZ2VXZWJTAXRLXHNVY2TQY1UB2RLXDNL1MDBHYVX3ZWZ2NRZQ==
X-Powered-By:ASP.NET日期:2019年3月15日星期五08:03:32 GMT
概述:
请求URL:wss://localhost:44391/sockjs-节点/616/kjiu00aa/websocket
请求方法:获取状态代码:400错误请求
UPD
如果我注释掉代码中使用HttpClient的唯一位置,那么错误仍然会显示
所以问题不在WebApi中,您可以这样尝试吗
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.Build());
});
一切都很简单 至少对我来说,这个错误是无用的 我不知道观察者是懒惰的,因此请求没有通过 UPD:
从5版本更新到7版本后,此错误不会显示。@KirkLarkin,稍后确定。也许我应该传递一个请求以获取其他内容?我尝试添加{withCredentials:true},但没有帮助您提供有关浏览器开发人员工具中显示的错误的更多信息吗?使用400失败的请求应该在网络选项卡中可见,并有助于诊断此问题。错误消息表明此问题与您在问题中提到的API端点无关<代码>wss://localhost:44391/sockjs-节点/…是通过Angular CLI连接回SPA服务器的web套接字连接,因此在此阶段很难诊断。下一步是查看服务器日志,看看在处理该请求时到底发生了什么。@KirkLarkin,这个项目是从默认的Visual Studio模板创建的,带有Angular和我的小改动。也许我应该在web api端或Angular端安装一个人?你能和startup.cs、controller csI共享全部startup.cs代码吗。未在控制器上触发断点=>requst dont传递Web Api。