问题描述
我在.net core 3.0中创建了一个Web应用程序(剃须刀页面).然后,我向其中添加了一个api控制器(均来自模板,只需单击几下).当我运行应用程序时,剃须刀页面有效,但api调用返回404.问题出在哪里,如何使它起作用?
I created a web app (razor pages) in .net core 3.0. Then I added an api controller to it (both from templates, just few clicks). When I run app, razor page works, but api call returns 404. Where is the problem and how can I make it work?
推荐答案
您需要配置启动以支持Web api和属性路由.
You need to configure your startup to support web api and attribute routing.
services.AddControllers()
添加对控制器和与API相关的功能的支持,但不添加视图或页面的支持.请参考 MVC服务注册.
services.AddControllers()
adds support for controllers and API-related features, but not views or pages. Refer to MVC service registration.
添加 endpoints.MapControllers
.请参阅迁移MVC控制器.
合并剃须刀页面和api之类的
Combine razor pages and api like:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddRazorPages()
.AddNewtonsoftJson();
services.AddControllers()
.AddNewtonsoftJson();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//other middlewares
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
这篇关于同一项目中的Razor页面和Webapi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!