解读ASP.NET 5 & MVC6系列(17):MVC中的其他新特性
2015-10-12 16:08
686 查看
(GlobalImport全局导入功能)
默认新建立的MVC程序中,在Views目录下,新增加了一个_GlobalImport.cshtml文件和
_ViewStart.cshtml平级,该文件的功能类似于之前Views目录下的web.config文件,之前我们在该文件中经常设置全局导入的命名空间,以避免在每个view文件中重复使用
@using xx.xx语句。
默认的示例如下:
@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地址的相关信息,实例如下:
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在文件上传方面,给了新的改进处理,举例如下:<form method="post" enctype="multipart/form-data"> <input type="file" name="files" id="files" multiple /> <input type="submit" value="submit" /> </form>
我们在前端页面定义上述上传表单,在接收可以使用MVC6中的新文件类型
IFormFile,实例如下:
[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系列
相关文章推荐
- 解读ASP.NET 5 & MVC6系列(16):自定义View视图文件查找逻辑
- 解读ASP.NET 5 & MVC6系列(15):MvcOptions配置
- 解读ASP.NET 5 & MVC6系列(14):View Component
- 解读ASP.NET 5 & MVC6系列(13):TagHelper
- 解读ASP.NET 5 & MVC6系列(12):基于Lamda表达式的强类型Routing实现
- 解读ASP.NET 5 & MVC6系列(11):Routing路由
- 解读ASP.NET 5 & MVC6系列(10):Controller与Action
- 解读ASP.NET 5 & MVC6系列(8):Session与Caching
- 解读ASP.NET 5 & MVC6系列(9):日志框架
- 解读ASP.NET 5 & MVC6系列(7):依赖注入
- 解读ASP.NET 5 & MVC6系列(6):Middleware详解
- 解读ASP.NET 5 & MVC6系列(5):Configuration配置信息管理
- 解读ASP.NET 5 & MVC6系列(4):核心技术与环境配置
- 解读ASP.NET 5 & MVC6系列(3):项目发布与部署
- ASP.NET中的Request和Respone对象的使用
- 解读ASP.NET 5 & MVC6系列(2):初识项目
- ASP.NET 5简介
- ASP.NET 打包下载文件
- ASP.NET 页生命周期概述
- asp.net repeater控件操作