我将 dotnet core 2.2 Web api 应用程序托管到本地 IIS。当我运行托管网站时,网站正在运行。我正在尝试从角度登录,但它不起作用。
It says 从源“http://localhost:4200”访问位于“http://192.168.43.143:100/Auth/Login”的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头关于所请求的资源。
Note: 它在本地工作。没有发生 CORS 策略问题
我在ConfigureServices中添加了cors策略,并提供了中间件来添加UseCors()。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyHeader()
.AllowAnyMethod().AllowAnyOrigin()
.SetIsOriginAllowed((host) => true).AllowCredentials());
});
services.Configure<MvcOptions>(options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowOrigin"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowOrigin");
app.UseMvc();
}
我安装的软件详细信息如下,
- 系统:Windows 10
- DotNet 核心 SDK:2.2.110 和 3.1.201
- Windows 服务器托管:2.2.1
下面给出基本代码供您参考。
点网核心Web API:
程序.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:4000")
.UseStartup<Startup>();
}
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin",
options => options.WithOrigins("*").AllowCredentials().AllowAnyHeader().AllowAnyMethod()
);
});
// DbContext and JWT implementation done
// Authorization filter added
services.Configure<MvcOptions>(options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowOrigin"));
});
//Dependence Injunction done
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// app.UseForwardedHeaders();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseAuthentication(); //it is used to authorize jwt tokens
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseCors();
app.UseMvc();
}
托管Web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\TestAPI.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
</system.webServer>
</location>
</configuration>
<!--ProjectGuid: 9aea96ef-cfc4-4231-9bfb-78f4efec933f-->
启动设置.json:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:4000",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
//"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"TestAPI": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "http://localhost:4000/values",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
角7:
给出了拦截器代码
const authReq = this.currentuser
? request.clone({
headers: request.headers.set('Authorization', 'Bearer ' + this.currentuser)
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
.set('Content-Type', request.headers.get('content-type') ?
request.headers.get('content-type') : 'application/json')
})
: request.clone({
headers: request.headers
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
.set('Content-Type', 'application/json')
});
return next.handle(authReq).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
// auto logout if 401 response returned from api
this.authenticationService.logout();
// tslint:disable-next-line: deprecation
location.reload(true);
}
return throwError(error);
}));
IIS Configuration image given below