[英]How do i add a web api to an existing asp.net mvc core 6 web application
I am trying to add a web API endpoint to an existing web application.我正在尝试将 web API 端点添加到现有的 web 应用程序。 How do I go about doing this?
我 go 如何做到这一点? Here is the GitHub link https://github.com/GrindingLife/BHFunctioning
这是 GitHub 链接https://github.com/GrindingLife/BHFunctioning
I have tried adding a scaffold of an API controller in the controller folder.我尝试在 controller 文件夹中添加 API controller 的脚手架。 When launched accessing the localhost/api does not work.
启动时访问 localhost/api 不起作用。 I do not know what to add to the Program.cs file.
我不知道要向 Program.cs 文件添加什么。 All the examples that I've seen are for startup.cs file instead of program.cs
我见过的所有示例都是针对 startup.cs 文件而不是 program.cs
Here is my program.cs file这是我的 program.cs 文件
using BHFunctioning.Controllers;
using BHFunctioning.Data;
using BHFunctioning.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole",
policy => policy.RequireRole("Administrator"));
});
builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddRoles<IdentityRole>()
.AddDefaultUI()
.AddDefaultTokenProviders();
builder.Services.AddSingleton<IFileProvider>(
new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
I have solved it, i just needed to add the following into Program.cs and call it using localhost:2444/api/{controller name}我已经解决了,我只需要将以下内容添加到 Program.cs 中并使用 localhost:2444/api/{controller name} 调用它
builder.Services.AddRazorPages();
builder.Services.AddControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.