.net Core mvc6等一些列了解

http://www.bsjobjob.com

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  _ViewImports.cshtml导入

@removeTagHelper 移除标签

Microsoft.AspNet.Mvc.TagHelpers 学习

标记帮助器是实现任何类ITagHelper接口。

但是,在创作标记帮助器时,你通常派生自TagHelper,执行这样的可以访问Process方法

TagHelper类还提供的异步版本 (ProcessAsync) 使用相同的参数

有关标记帮助程序 Pascal 大小写形式类和属性的名称转换为其降低 kebab 用例。 因此,若要使用MailTo属性中AspAction

你还可以使用[HtmlTargetElement]若要更改目标元素的名称。 例如,如果你想BoldTagHelper到目标<MyBold>标记,则将使用以下属性

public class WebsiteInformationTagHelper : TagHelper {

public WebsiteContext Info { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output) {

output.TagName = "section";

output.Content.SetHtmlContent( $@"<ul><li><strong>Version:</strong> {Info.Version}</li> <li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li> <li><strong>Approved:</strong> {Info.Approved}</li> <li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");

output.TagMode = TagMode.StartTagAndEndTag;

} }

<website-information info="new WebsiteContext { Version = new Version(1, 3), CopyrightYear = 1638, Approved = true, TagsToShow = 131 }" />

 

asp-controller用于将相关联的控制器将用于生成 URL。 指定的控制器必须存在于当前项目。 下面的代码列

<a asp-controller="Speaker" asp-action="Index">All Speakers</a> 写法

<a href="/Speaker">All Speakers</a> 最后生成

如果该属性asp-actionIndex,则任何操作不追加到的 URL,从而导致默认Index所调用方法。

asp-route-是一个通配符路由前缀。 任何 put 后尾随 dash 将解释为潜在的路由参数值

<a asp-controller='Speaker' asp-action='Detail' asp-route-id=@Model.SpeakerId>SpeakerId: @Model.SpeakerId</a> 写法

<a href='/Speaker/Detail/12'>SpeakerId: 12</a> 生成效果

asp-all-route-data可以创建的字典的键/值对,其中键是参数名称,值是与该项关联的值。

var dict = new Dictionary<string, string> { {"speakerId", "11"}, {"currentYear", "true"} };

<a asp-route="speakerevalscurrent" asp-all-route-data="dict">SpeakerEvals</a> 写法

http://localhost/Speaker/EvaluationsCurrent?speakerId=11&currentYear=true 生成效果

asp-fragment定义要追加到 URL 的 URL 片段。 定位点标记帮助程序将添加的哈希字符 (#)。

 如果要创建一个标记:生成的 URL 将是: http://localhost/Speaker/Evaluations#SpeakerEvaluations

asp-area设置 ASP.NET Core 使用设置适当的路由的区域名称。 下面是如何区域属性将导致重新路由映射的示例

<a asp-action="AboutBlog" asp-controller="Home" asp-area="Blogs">Blogs About</a> 写法

<a href="/Blogs/Home/AboutBlog">Blogs About</a> 生成效果

asp-protocol可用于指定一种协议 (如https) 在你的 URL。 

<a asp-protocol="https" asp-action="About" asp-controller="Home">About</a> 写法

<a href="https://localhost/Home/About">About</a>

asp-for属性 

<label asp-for="Email"></label>

下拉绑定

<select asp-for="Country" asp-items="Model.Countries"></select>

下拉枚举绑定

<select asp-for="EnumCountry" asp-items="Html.GetEnumSelectList<CountryEnum>()"> >

正确<option>将选择的元素 (包含selected="selected"属性) 具体取决于当前Country值。

请求CacheTagHelper将显示当前日期/时间

缓存标记帮助程序是依赖于内存缓存服务。 如果尚未添加,缓存标记帮助器将服务添加

<Cache enabled="true"> Current Time Inside Cache Tag Helper: @DateTime.Now </Cache>

IDistributedCache接口容器传递到分布式缓存标记帮助器的构造函数。 如果没有特定的具体实现IDistributedCache已在中创建ConfigureServices,通常会在 startup.cs,找到然后分布式缓存标记帮助程序将使用相同的内存中提供程序将缓存的数据存储为基本缓存标记帮助器。

有的两个实现IDistributedCache内置到 ASP.NET 核心。 一个基于Sql Server和其他基于Redis

一个有效的示例environment标记帮助程序是:

这些值与从 ASP.NET Core 静态属性返回的当前值进行比较HostingEnvironment.EnvironmentName。 此值是以下之一:过渡;开发生产。 比较不区分大小写。分别是开发环境Development,项目过度环境Staging(一般最后一次测试) 生产环境 Production Linux 下是区分他们的大小写的

设置的值保留在launchSettings.json文件 中 在项目属性中的Debug设置

约定: Development, Staging,和Production

img(<img>) 标记。 它需要src标记以及boolean属性asp-append-version

若要激活图像标记帮助器,src 属性都需要<img>元素。

<img src="~/images/asplogo.png" asp-append-version="true" />

<img src="/images/asplogo.png?v=Kl_dqr9NVtnMdsM2MUg4qthUnWZm5T1fCEimBPWDNgM"/>

 asp-page-handler 生成提交到页面定义的各个处理程序方法的 URL。 未指定 asp-page,因为示例已链接到当前页面。

选中按钮时,向服务器发送窗体 POST 请求。 按照惯例,根据方案 OnPost[handler]Async 基于 handler 参数的值来选择处理程序方法的名称。

因为本示例中 handler 是 delete,因此 OnPostDeleteAsync 处理程序方法用于处理 POST 请求。 如果 asp-page-handler 设置为不同值(如 remove),则选择名称为 OnPostRemoveAsync 的页面处理程序方法。

Async 命名后缀为可选

public async Task<IActionResult> OnPostDeleteAsync(int id)
{
    var contact = await _db.Customers.FindAsync(id);

    if (contact != null)
    {
        _db.Customers.Remove(contact);
        await _db.SaveChangesAsync();
    }

    return RedirectToPage();
}

 @page 使文件转换为一个 MVC 操作 ,这意味着它将直接处理请求,而无需通过控制器处理

显示使用 PageModel 类的类似页面

 Pages/Index2.cshtml

@page
@using RazorPagesIntro.Pages
@model IndexModel2

<h2>Separate page model</h2>
<p>
    @Model.Message
</p>

Pages/Index2.cshtml.cs“代码隐藏”文件:

using Microsoft.AspNetCore.Mvc.RazorPages;
using System;

namespace RazorPagesIntro.Pages
{
    public class IndexModel2 : PageModel
    {
        public string Message { get; private set; } = "PageModel in C#";

        public void OnGet()
        {
            Message += $" Server time is { DateTime.Now }";
        }
    }
}

XSRF/CSRF 和 Razor 页面

无需为防伪验证编写任何代码。 Razor 页面自动将防伪标记生成过程和验证过程包含在内。

A元素

属性描述
asp-controllerController的名称
asp-actionAction的名称
asp-host网站的Host
asp-fragmentURL的fragment名称
asp-protocol网站协议(http或https)
asp-routeRoute名称
asp-route- 
href默认属性,如果href有值,则其它属性都不能设置任何值。

Form元素

属性描述
asp-controllerController的名称
asp-actionAction的名称
asp-anti-forgery 
asp-route- 
action默认属性,如果action有值,则其它属性都不能设置任何值。

Input元素

属性描述
asp-for模型字段的名称
asp-format设置Type格式,具体如下:
格式标准类型
HiddenInputhidden
Passwordpassword
Texttext
PhoneNumbertel
Urlurl
EmailAddressemail
Datedate
DateTimedatetime
DateTime-localdatetime-local
Timetime
Byte/SByte/Int16/UInt16/Int32/UInt32/Int64/UInt64/Single/Doublenumber
Booleancheckbox
Decimaltext
Stringtext
IFormFilefile
IEnumerable`IFormFilefile

其中关于时间的具体格式如下:

属性描述
date{0:yyyy-MM-dd}
datetime{0:yyyy-MM-ddTHH:mm:ss.fffK}
datetime-local{0:yyyy-MM-ddTHH:mm:ss.fff}
time{0:HH:mm:ss.fff}

Label元素

属性描述
asp-for模型字段的名称

textarea元素

属性描述
asp-for模型字段的名称

span元素

属性描述
asp-validation-for模型字段的名称

div元素

属性描述
asp-validation-aummaryValidationSummary枚举值:
ValidationSummary.All
ValidationSummary.ModelOnly
ValidationSummary.None。

验证描述类型,只有选择了ValidationSummary.All和ValidationSummary.ModelOnly才能渲染该div元素。

select元素

属性描述
asp-for模型字段名称
asp-items模型字段名称

link元素

属性描述
asp-href-include 
asp-href-exclude 
asp-fallback-href默认href加载失败时的备用地址
asp-fallback-href-include 
asp-fallback-href-exclude 
asp-fallback-test-class判断加载失败时用到的class样式
asp-fallback-test-property判断加载失败时用到的class样式中的属性
asp-fallback-test-value判断加载失败时用到的class样式中的属性对应的值
asp-file-version 
href默认加载的css文件地址。

script元素

属性描述
asp-src-include 
asp-src-exclude 
asp-fallback-src备用js文件地址
asp-fallback-src-include 
asp-fallback-src-exclude 
asp-fallback-test判断默认js文件是否加载成功用到的对象
asp-file-version 
src默认的js文件地址。

 

Cache

属性描述
vary-by 
vary-by-header 
vary-by-query 
vary-by-route 
vary-by-cookie 
vary-by-user 
expires-on 
expires-after 
expires-sliding 
priority 
enabled.

 

分部视图

@Html.Partial("AuthorPartial") 
@await Html.PartialAsync("AuthorPartial") 
@{ Html.RenderPartial("AuthorPartial"); }流式处理结果RenderPartialRenderPartialAsync可能在某些情况下更好地执行。 但是,在大多数情况下,建议你使用PartialPartialAsync

 

如果你的视图需要执行代码,建议的模式是使用视图组件而不是分部视图。

视图组件由两部分组成: 类 (通常派生自ViewComponent) 并在结果返回 (通常视图)。 与控制器,一样视图组件可以是 POCO,但大多数开发人员将想要的方法和属性可用来利用派生自ViewComponent

  • 创建的类名称与后缀的结束位置ViewComponent
  • 与控制器,一样查看组件必须是公共的、 有非嵌套的和非抽象类。 视图组件名称是删除了"ViewComponent"后缀的类名称。 它还可以显式指定使用ViewComponentAttribute.Name属性。
  • 运行时中搜索以下路径中的视图:

  • 视图组件来定义其逻辑中的InvokeAsync返回方法IViewComponentResult

  • 视图 /<controller_name > /Components/<view_component_name > /<view_name >
  • 视图/共享/组件/<view_component_name > /<view_name >
  • 若要使用视图组件,请调用以下命令,在视图内:
  • Views/Shared/Components/PriorityList/Default.cshtml
  • @Component.InvokeAsync("Name of view component", <anonymous type containing parameters>)
  • @await Component.InvokeAsync("PriorityList", new { maxPriority = 4, isDone = true })

<vc:priority-list max-priority="2" is-done="false"> </vc:priority-list>

有关标记帮助程序 Pascal 大小写形式类和方法的参数转换为其降低 kebab 用例PriorityList

注意: 若要将视图组件用作标记帮助程序,你必须注册包含视图组件使用的程序集@addTagHelper指令。 例如,如果你视图组件是一个程序集称为"MyWebApp"中,添加以下指令到_ViewImports.cshtml文件:

[ViewComponent(Name = "PriorityList")]

public class XYZ : ViewComponent

IViewComponentResult 返回对象

避免神奇的字符串

如果你想编译时间安全性,可以将硬编码视图组件名称替换类名称。 创建不带"ViewComponent"后缀的视图组件:添加using语句与你 Razor 查看文件,并使用nameof运算符:

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using ViewComponentSample.Models;

namespace ViewComponentSample.ViewComponents {

public class PriorityList : ViewComponent {

private readonly ToDoContext db; public PriorityList(ToDoContext context) {

db = context;

}

public async Task<IViewComponentResult> InvokeAsync( int maxPriority, bool isDone) { var items = await GetItemsAsync(maxPriority, isDone); return View(items);

}

private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone) {

return db.ToDo.Where(x => x.IsDone == isDone && x.Priority <= maxPriority).ToListAsync(); }

}

}

@await Component.InvokeAsync(nameof(PriorityList), new { maxPriority = 4, isDone = true })

路由配置

app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); });

app.UseMvcWithDefaultRoute(); 路由快速配置

Microsoft.AspNet.HttpFeature 依赖获取HttpContext.GetFeature<IHttpConnectionFeature>();

[Route("")] 路由绑定

[HttpGet("/products")] 请求绑定

IRouteTemplateProvider 使用应用程序模型自定义属性的路由

[Area("Blog")] 域访问

IFormFile 文件上传

[HttpPost("UploadFiles")]

public async Task<IActionResult> Post(List<IFormFile> files) {

long size = files.Sum(f => f.Length); // full path to file in temp location

var filePath = Path.GetTempFileName();

foreach (var formFile in files) {

if (formFile.Length > 0) {

using (var stream = new FileStream(filePath, FileMode.Create)) {

await formFile.CopyToAsync(stream);

}

}

} // process uploaded files

// Don't rely on or trust the FileName property without validation.

return Ok(new { count = files.Count, size, filePath}); }

IFormFile可以在直接作为操作方法参数或作为视图模型属性,如上所示。

public byte[] AvatarImage { get; set; }

public class RegisterViewModel {

// other properties omitted

public IFormFile AvatarImage { get; set; }

新建文件型IFormFile

你可以将服务注入到视图使用@inject指令。

语法@inject:@inject <type> <name>

@inject StatisticsService StatsService

ConfigureServicesStartup.cs:

public void ConfigureServices(IServiceCollection services) {

services.AddMvc();

services.AddTransient<IToDoItemRepository, ToDoItemRepository>();

services.AddTransient<StatisticsService>();

services.AddTransient<ProfileOptionsService>();

}

[FromServices]

可能有必要将服务注入作为参数传递给的操作方法

public IActionResult About([FromServices] IDateTime dateTime) {

ViewData["Message"] = "Currently on the server the time is " + dateTime.Now; return View();

}

public void ConfigureServices(IServiceCollection services) {

// Required to use the Options<T> pattern

services.AddOptions(); // Add settings from configuration services.Configure<SampleWebSettings>(Configuration);

services.AddMvc(); // Add application services.

services.AddTransient<IDateTime, SystemDateTime>();

}

public class SettingsController : Controller
{

   ///针对appconfig 配置的节点做配置
    private readonly SampleWebSettings _settings;

    public SettingsController(IOptions<SampleWebSettings> settingsOptions)
    {
        _settings = settingsOptions.Value;
    }

    public IActionResult Index()
    {
        ViewData["Title"] = _settings.Title;
        ViewData["Updates"] = _settings.Updates;
        return View();
    }
}

内置的中间件

身份验证提供的身份验证支持。
CORS配置跨域资源共享。
响应缓存提供对缓存响应支持。
响应压缩提供用于压缩响应的支持。
路由定义和约束请求路由。
会话提供用于管理用户会话的支持。
静态文件为静态文件和目录浏览提供服务提供支持。
URL 重写中间件用于重写 Url,并将请求重定向的支持。

实现自己的中间件

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use((context, next) =>
        { 

            // 不根据扩展实现
            var cultureQuery = context.Request.Query["culture"];
            if (!string.IsNullOrWhiteSpace(cultureQuery))
            {
                var culture = new CultureInfo(cultureQuery);

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;
            }

            // Call the next delegate/middleware in the pipeline
            return next();

        });

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(
                $"Hello {CultureInfo.CurrentCulture.DisplayName}");
        });

    }
}

根据类实现中间件

 

using Microsoft.AspNetCore.Http;
using System.Globalization;
using System.Threading.Tasks;

namespace Culture
{
    public class RequestCultureMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestCultureMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext context)
        {
            var cultureQuery = context.Request.Query["culture"];
            if (!string.IsNullOrWhiteSpace(cultureQuery))
            {
                var culture = new CultureInfo(cultureQuery);

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;

            }

            // Call the next delegate/middleware in the pipeline
            return this._next(context);
        }
    }
}

using Microsoft.AspNetCore.Builder;

namespace Culture
{
    public static class RequestCultureMiddlewareExtensions
    {

      //扩展方法 IApplicationBuilder
        public static IApplicationBuilder UseRequestCulture(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestCultureMiddleware>();
        }
    }
}

 

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRequestCulture();

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(
                $"Hello {CultureInfo.CurrentCulture.DisplayName}");
        });

    }
}

中间件应遵循显式依赖关系原则通过公开其依赖项在其构造函数。 每次构造中间件应用程序生存期。 请参阅每个请求的依赖关系下面如果你需要与请求中的中间件共享服务。

添加基架工具 通过命令生成 EF

Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Utils

dotnet restore
dotnet aspnet-codegenerator razorpage -m Student -dc SchoolContext -udl -outDir Pages\Students --referenceScriptLibraries

命令参数

参数描述
-m模型的名称。
-dc数据上下文。
-udl使用默认布局。
-outDir用于创建视图的相对输出文件夹路径。
--referenceScriptLibraries向“编辑”和“创建”页面添加 _ValidationScriptsPartial

EF 上下文不是线程安全: 请勿尝试执行并行的多个操作

EF OnModelCreating 派生数据模型

protected override void OnModelCreating(ModelBuilder modelBuilder) {

modelBuilder.Entity<Car>() .HasKey(c => c.LicensePlate);

}

IsRequire()RequiredProperty 
Ignore()NotMappedmodelBuilder
HasKeyKeyEntity
HasMaxLengthMaxLengthProperty 
IsConcurrencyTokenConcurrencyCheck(并发)Property 
HasForeignKeyForeignKey 
HasOne WithMany  
HasIndex IsUnique索引Entity
HasAlternateKey备用建Entity
HasBaseType如果模型中显式包含两个或多个继承的类型,EF 将仅设置继承Entity
   
 [Timestamp] public byte[] RowVersion { get; set; }处理并发
 FromSqlEntity
CreateCommandSystem.Data.Common 
   
   
   
   
   
   
   
   
   
   
   

 

 

_GlobalImport.cshtml 经常设置全局导入的命名空间

IViewLocationExpander、RazorViewEngine。View文件的路径进行控制

services.AddMvc().Configure<MvcOptions>(options => {

options.ViewEngines.Clear(); options.ViewEngines.Add(typeof(ThemeViewEngine));

} ); mvcoptions 到底有哪些?

ProducesAttribute 特性[Produces("application/json")] 声明action 返回的数据格式

services.Configure<MvcOptions>(options=>options.Filters.Add(new ProducesAttribute("application/json"))

); 可以设置全局的ProducesAttribute 特性

 

 

 

 

 

 

转载于:https://my.oschina.net/stuyun/blog/1592934

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值