我一直致力于将应用程序从过时的 DNX 迁移到 ASP.NET Core 2.0。在这样做的过程中,我们发现命名空间和 API 几乎没有变化,例如Microsoft.AspNet
to Microsoft.AspNetCore
。尽管我已经能够找到并修复大部分更改,但以下更改给我带来了问题:
在继承自的类中Route
, 之内RouteAsync(RouteContext context)
方法,使用 DNX 是context.IsHandled = true;
,我如何表示现在已使用 ASP.NET Core 2.0 处理此问题?
我尝试从 GitHub 查找更改历史记录,但似乎没有与此相关的内容。
不再需要调用context.IsHandled
from RouteAsync
。如果您这样做,框架就会知道跳到下一条路线return
没有Task
。如果您返回一个任务,那么框架将处理(处理)它。
旧的 DNX / MVC6 / 预览代码
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;
}
}
}
新的 .NET Core 1.x / .NET Core 2.x 代码
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 进行了更新):启动后更改MVC6的路由集合 https://stackoverflow.com/q/32565768
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)