我一直在努力将应用程序从过时的DNX迁移到ASP.NET Core 2.0。在这样做的同时,它发现名称空间和API(例如Microsoft.AspNet
到Microsoft.AspNetCore
)几乎没有变化。虽然我已经能够找到并修复大部分更改,但下面的内容对我来说是个问题:
在继承自Route
的类中,在RouteAsync(RouteContext context)
方法中,DNX为context.IsHandled = true;
,我如何表示现在已经使用ASP.NET Core 2.0处理了这个?
我试图从GitHub找到更改历史记录,但似乎没有与此相关。
答案 0 :(得分:3)
不再需要从context.IsHandled
致电RouteAsync
。如果return
没有Task
,框架会知道跳到下一个路线。如果你返回一个任务,那么框架将处理(处理)它。
public async Task RouteAsync(RouteContext context)
{
var requestPath = context.HttpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/')
{
// Trim the leading slash
requestPath = requestPath.Substring(1);
}
// Get the page id that matches.
TPrimaryKey id;
//If this returns false, that means the URI did not match
if (!GetPageList().TryGetValue(requestPath, out id))
{
return;
}
//Invoke MVC controller/action
var oldRouteData = context.RouteData;
var newRouteData = new RouteData(oldRouteData);
newRouteData.Routers.Add(_target);
newRouteData.Values["controller"] = _controller;
newRouteData.Values["action"] = _action;
// This will be the primary key of the database row.
// It might be an integer or a GUID.
newRouteData.Values["id"] = id;
try
{
context.RouteData = newRouteData;
await _target.RouteAsync(context);
}
finally
{
// Restore the original values to prevent polluting the route data.
if (!context.IsHandled)
{
context.RouteData = oldRouteData;
}
}
}
public async Task RouteAsync(RouteContext context)
{
var requestPath = context.HttpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/')
{
// Trim the leading slash
requestPath = requestPath.Substring(1);
}
// Get the page id that matches.
TPrimaryKey id;
//If this returns false, that means the URI did not match
if (!GetPageList().TryGetValue(requestPath, out id))
{
return;
}
//Invoke MVC controller/action
var routeData = context.RouteData;
routeData.Values["controller"] = _controller;
routeData.Values["action"] = _action;
// This will be the primary key of the database row.
// It might be an integer or a GUID.
routeData.Values["id"] = id;
await _target.RouteAsync(context);
}
此处为完整代码(针对.NET Core 1/2更新):Change route collection of MVC6 after startup