我是ASP.NET Core的新手,我搜索了很多但仍然对Core 2.1中的路由感到困惑。
所以,我创建了一个示例项目选择API作为模板,VS创建了如下内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// 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.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc();
}
但我不需要MVC提供的所有功能,因为我的项目不使用视图。
任何帮助将不胜感激
是的虽然我们经常使用MVC路由,但Routing是一个不依赖于MVC的项目。
与ASP.NET Core一起使用时,Routing在场景后面作为RouterMiddleware运行。如果你不想MVC,只需构建一个路由器:
private IRouter BuildRouter(IApplicationBuilder applicationBuilder)
{
var builder = new RouteBuilder(applicationBuilder);
// use middlewares to configure a route
builder.MapMiddlewareGet("/api/hello", appBuilder => {
appBuilder.Use(async (context,next) => {
context.Response.Headers["H1"] = "Hello1";
await next();
});
appBuilder.Use(async (context,next) => {
context.Response.Headers["H2"] = "Hello2";
await next();
});
appBuilder.Run(async (context) => {
await context.Response.WriteAsync("Hello,world");
});
});
builder.MapMiddlewarePost("/api/hello", appBuilder => {
// ...
});
// ....
return builder.Build();
}
并注册路由器中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseRouter(BuildRouter(app));
}
这是一个截图,它的工作原理:
是。来自https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.1:
var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);
routeBuilder.MapGet("hello/{name}", context => {
var name = context.GetRouteValue("name");
return context.Response.WriteAsync($"Hi, {name}!"); });
var routes = routeBuilder.Build(); app.UseRouter(routes);
或者,如果要将其实现为自定义中间件,并且只需要基本路由:
来自:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1
public class Startup
{
private static void HandleMapTest1(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Map Test 1");
});
}
public void Configure(IApplicationBuilder app)
{
app.Map("/map1", HandleMapTest1);
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from non-Map delegate. <p>");
});
}
}
或者如果您需要更多路由功能,请参阅itmius'回答https://stackoverflow.com/a/52377807/2085502
解决了,使用以下启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddApiExplorer()
.AddAuthorization()
.AddJsonFormatters()
.AddCors();
}
// 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.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
感谢所有试图帮助我的人!