如何解决将.net Core 3.1 Web API发布到远程服务器时遇到问题
发布后,我在远程服务器上运行asp.net core 3.1 Web API时遇到问题。该API在我的PC上运行良好,但是当我发布该API时,所有API端点都返回错误404。我昂首阔步的文档页面swagger / index.html也返回相同的错误。
下面是Program.cs代码
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
我的启动cs文件如下
public class Startup
{
private readonly IWebHostEnvironment _env;
private readonly IConfiguration _configuration;
//public static IMvcBuilder ConfigureApiBehaviorOptions(this IMvcBuilder builder,Action<ApiBehaviorOptions> setupAction);
public Startup(IWebHostEnvironment env,IConfiguration configuration)
{
_env = env;
_configuration = 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)
{
try
{
// use sql server db in production and sqlite db in development
//if (_env.IsProduction())
// services.AddDbContext<DataContext,SqlDataContext>();
//else
// services.AddDbContext<DataContext,SqliteDataContext>();
//services.AddDbContext<DataContext,SqlDataContext>();
services.AddDbContext<DataContext,SqlDataContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("SQLServerdb")));
services.AddCors();
services.AddControllers();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
// configure strongly typed settings objects
var appSettingsSection = _configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// enabling API documentation
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",new Microsoft.OpenApi.Models.OpenApiInfo
{
Version = "v1",Title = "x",Description = "x",TermsOfService = null,Contact = new Microsoft.OpenApi.Models.OpenApiContact()
{
Name = "x",Email = "x",Url = null
}
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory,xmlFile);
c.IncludeXmlComments(xmlPath);
});
// enabling Cookies
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
}).AddCookie("Cookies",options =>
{
options.Cookie.Name = globals.APISessionKey;
options.Cookie.SameSite = SameSiteMode.None;
options.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = redirectContext =>
{
redirectContext.HttpContext.Response.StatusCode = 401;
return Task.CompletedTask;
}
};
});
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.Events = new JwtBearerEvents()
{
OnTokenValidated = context =>
{
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
var theContext = context.HttpContext;
var userId = int.Parse(context.Principal.Identity.Name);
var user = userService.GetById(context.HttpContext,userId);
if (user == null)
{
// return unauthorized if user no longer exists
context.Fail("Unauthorized");
}
return Task.CompletedTask;
}
};
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,IssuerSigningKey = new SymmetricSecurityKey(key),ValidateIssuer = false,ValidateAudience = false
};
});
// custom validation responses CustomBadRequest
//services.Configure<ApiBehaviorOptions>(a =>
//{
// a.InvalidModelStateResponseFactory = context =>
// {
// var problemDetails = new CustomBadRequest(context);
// return new BadRequestObjectResult(problemDetails)
// {
// // ContentTypes = { "application / problem + json","application / problem + xml" } // these requires cross origin resource what what (cors)
// };
// };
//});
}
catch (Exception ex)
{
Console.WriteLine("ConfigureServices _ERROR: " + ex.Message);
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IWebHostEnvironment env,DataContext dataContext)
{
try
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
dataContext.Database.Migrate();
app.UseHttpsRedirection();
app.UseRouting();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// Enable middle ware to serve swagger-ui (HTML,JS,CSS etc.),specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v1/swagger.json","My API V1 (RELEASE)");
//c.SwaggerEndpoint("/swagger/v1/swagger.json","My API V1 (DEBUG)");
/*To serve the Swagger UI at the app's root (http://localhost:<port>/),set the RoutePrefix property to an empty string:
c.SwaggerEndpoint("/swagger/v1/swagger.json","My API V1");
c.RoutePrefix = string.Empty;*/
});
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//app.UseHttpsRedirection();
//app.UseRouting();
//app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
}
catch (Exception ex)
{
Console.WriteLine("Configure _ERROR: " + ex.Message);
}
}
}
}
有什么我想念的东西吗?我的API与blazor服务器应用程序使用相同的解决方案,该应用程序在API无法正常运行的同一服务器上运行良好。
我曾尝试自行修复该问题并在互联网上进行搜索,但没有找到任何可以帮助我解决此问题的方法。非常感谢您的帮助。
解决方法
项目的Swagger设置没有问题。看来您正在将DotNet Core应用程序(Core Web API和Blazor服务应用程序)部署到IIS Web服务器。
一般来说,如果这些应用程序在本地正常运行,但在远程Web服务器中返回HTTP错误。托管环境可能配置不正确。
例如,托管DotNet Core应用程序时,需要以下IIS托管捆绑软件。
下载URL(直接下载)。
https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.7-windows-hosting-bundle-installer
此外,应该使用IUSR
帐户或Everyone
帐户正确访问发布位置,即网站根目录。它取决于应用程序池标识的帐户。
随时让我知道问题是否仍然存在。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。