asp.net core MVC路由添加.html伪静态url时报错
asp.net core mvc
希望 url链接中以 .html
结尾,伪静态
效果
路由配置如下
endpoints.MapControllerRoute(
name: "default_page",
pattern: "{controller}/{action}.html",
defaults: new { controller = "Home", action = "list" });
控制器代码为
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace YESCMS.Controllers
{
public class IssuesCenterController : ControllerBase
{
public IssuesCenterController()
{
}
public class IndexViewModel
{
public int PageIndex { get; set; }
public int PageTotal { get; set; }
public List<ItemModel> Data { get; set; }
public class ItemModel
{
public string ID { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
public string CreateUser { get; set; }
public string CreateUserName { get; set; }
public bool IsOpen { get; set; }
public int Status { get; set; }
}
}
public IActionResult List(string filter = "", int page = 1)
{
var query = entities.data_Issues.AsNoTracking().OrderByDescending(o => o.CreateTime);
int pageSize = 20;
var total = query.Count();
IndexViewModel viewModel = new IndexViewModel();
viewModel.PageTotal = total / pageSize + (total % pageSize > 0 ? 1 : 0);
viewModel.Data = (from a in query.Skip((page - 1) * pageSize).Take(pageSize)
join b in entities.sys_User on a.CreateUser equals b.UserID
orderby a.CreateTime descending
select new IndexViewModel.ItemModel()
{
ID = a.ID,
CreateTime = a.CreateTime,
CreateUser = a.CreateUser,
Status = a.Status,
Title = a.Title,
CreateUserName = b.UserName,
IsOpen = a.IsOpen
}).ToList();
return View(viewModel);
}
/// <summary>
/// 添加提问
/// </summary>
/// <returns></returns>
public IActionResult Add()
{
return View("Add");
}
}
}
访问报错:
http://localhost:55742/issues/add.html
错误。
处理您的请求时发生错误。
请求 ID: 00-fa080328ab53cc43a320a58124899fe4-842fd398a465bf40-00
请求路径: /issues/add.html
异常信息: The request matched multiple endpoints. Matches: YESCMS.Controllers.IssuesController.List (YESCMS) YESCMS.Controllers.IssuesController.Add (YESCMS)
堆栈跟踪: at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState) at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ProcessFinalCandidates(HttpContext httpContext, CandidateState[] candidateState) at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.Select(HttpContext httpContext, CandidateState[] candidateState) at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.SelectAsync(HttpContext httpContext, CandidateSet candidateSet) at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.SelectEndpointWithPoliciesAsync(HttpContext httpContext, IEndpointSelectorPolicy[] policies, CandidateSet candidateSet) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatch|8_1(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task matchTask) at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context) at YESCMS.Startup.<>c__DisplayClass5_0.<<Configure>b__5>d.MoveNext() in E:\GZ\GZBlog\YESCMS\Startup.cs:line 146 --- End of stack trace from previous location --- at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
内部异常:
参考:
.net core3.1路由配置伪链接该怎么配置_已解决_博问_博客园 (cnblogs.com)
解决方案
利用动态路由DynamicRouteValueTransformer
public class YEDefaultRouteValueTransformer : DynamicRouteValueTransformer
{
public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
return await Task.Run(() =>
{
return values;
});
}
}
路由配置:
//endpoints.MapControllerRoute(
// name: "default_page",
// pattern: "{controller}/{action}.html");
//endpoints.MapControllerRoute(
// name: "default_page",
// pattern: "{controller}/{action}/page.html");
endpoints.MapDynamicControllerRoute<YEDefaultRouteValueTransformer>("/{controller}/{action}.html");
// 约束action只能是list,只有list才支持分页,不约束的话 [controller]/add/1.html 也能匹配进来,但是page这个参数是无效参数
endpoints.MapDynamicControllerRoute<YEDefaultRouteValueTransformer>("/{controller}/{action:regex(^list$)}/{page}.html");
路由约束参考: .NET Core中的路由约束
也可以拆分 YEDefaultRouteValueTransformer 为两个类
需要在 Startup.cs
的ConfigureServices
(IServiceCollection services) 中注册组件
services.AddSingleton<YEDefaultRouteValueTransformer>();