把旧系统迁移到.Net Core 2.0 日记(7) Tag Helpers /ResponseCache

时间:2023-03-09 01:42:01
把旧系统迁移到.Net Core 2.0 日记(7) Tag Helpers /ResponseCache

Tag Helpers是Html Helpers的一种替换

比如,原来的视图模型定义是这样的:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
</div>
</div>

在新版MVC中,我们可以使用Tag Helper进行定义:

<form asp-controller="Account" asp-action="Register" method="post" class="form-horizontal" role="form">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>

这样方便了前端开发人员了,但我没什么感觉,因为我是Full Stack Develop

如果要用,可以参考这篇文章: http://www.cnblogs.com/TomXu/p/4496480.html

现在没有outputCache的attribute了, 取代的是 Microsoft.AspNetCore.ResponseCaching

[ResponseCache(VaryByHeader ="Accept-Encoding", Location = ResponseCacheLocation.Any, Duration = )]
public IActionResult About()
{
}

如果要用VaryByQueryKeys, 要先引用Cache中间件,否则会报错  InvalidOperationException: 'VaryByQueryKeys' requires the response cache middleware.

修改 Startup.cs ,在ConfigureServices 和Configure 两个方法中添加如下代码:

public class Startup
{
... public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching(); ...
} public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseResponseCaching(); ...
}
}