(GlobalImport全局导入功能)
默认新建立的MVC程序中,在Views目录下,新增加了一个 _GlobalImport.cshtml 文件和 _ViewStart.cshtml 平级,该文件的功能类似于之前Views目录下的web.config文件,之前我们在该文件中经常设置全局导入的命名空间,以避免在每个view文件中重复使用 @using xx.xx 语句。
默认的示例如下:
1
2
3
@ using BookStore
@ using Microsoft.Framework.OptionsModel
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
上述代码表示,引用 BookStore 和 Microsoft.Framework.OptionsModel 命名空间,以及 Microsoft.AspNet.Mvc.TagHelpers 程序集下的所有命名空间。
关于addTagHelper功能,我们已经在TagHelper中讲解过了
注意,在本例中,我们只引用了 BookStore 命名空间,并没有引用 BookStore.Controllers 命名空间,所以我们在任何视图中,都无法访问 HomeController 类(也不能以 Controllers.HomeController 的形式进行访问),希望微软以后能加以改进。
获取IP相关信息
要获取用户访问者的IP地址相关信息,可以利用依赖注入,获取 IHttpConnectionFeature 的实例,从该实例上可以获取IP地址的相关信息,实例如下:
1
2
3
4
5
6
7
8
var connection1 = Request.HttpContext.GetFeature<IHttpConnectionFeature>();
var connection2 = Context.GetFeature<IHttpConnectionFeature>();
var isLocal = connection1.IsLocal; //是否本地IP
var localIpAddress = connection1.LocalIpAddress; //本地IP地址
var localPort = connection1.LocalPort; //本地IP端口
var remoteIpAddress = connection1.RemoteIpAddress; //远程IP地址
var remotePort = connection1.RemotePort; //本地IP端口
类似地,你也可以通过 IHttpRequestFeature 、 IHttpResponseFeature 、 IHttpClientCertificateFeature 、 IWebSocketAcceptContext 等接口,获取相关的实例,从而使用该实例上的特性,上述接口都在命名空间 Microsoft.AspNet.HttpFeature 的下面。
文件上传
MVC6在文件上传方面,给了新的改进处理,举例如下:
1
2
3
4
< form method = "post" enctype = "multipart/form-data" >
< input type = "file" name = "files" id = "files" multiple />
< input type = "submit" value = "submit" />
</ form >
我们在前端页面定义上述上传表单,在接收可以使用MVC6中的新文件类型 IFormFile ,实例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[HttpPost]
public async Task<IActionResult> Index(IList<IFormFile> files)
{
foreach (var file in files)
{
var fileName = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim( '"' ); // beta3版本的bug,FileName返回的字符串包含双引号,如"fileName.ext"
if (fileName.EndsWith( ".txt" )) // 只保存txt文件
{
var filePath = _hostingEnvironment.ApplicationBasePath + "\\wwwroot\\" + fileName;
await file.SaveAsAsync(filePath);
}
}
return RedirectToAction( "Index" ); // PRG
}
查看更多关于解读ASP.NET 5 & MVC6系列教程(17):MVC中的其他新特性的详细内容...