解读ASP.NET 5 & MVC6系列(17):MVC中的其余新特性

(GlobalImport全局导入功能)

默认新创建的MVC程序中,在Views目录下,新增长了一个_GlobalImport.cshtml文件和_ViewStart.cshtml平级,该文件的功能相似于以前Views目录下的web.config文件,以前咱们在该文件中常常设置全局导入的命名空间,以免在每一个view文件中重复使用@using xx.xx语句。
默认的示例以下:html

@using BookStore
@using Microsoft.Framework.OptionsModel
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

上述代码表示,引用BookStoreMicrosoft.Framework.OptionsModel命名空间,以及Microsoft.AspNet.Mvc.TagHelpers程序集下的全部命名空间。前端

关于addTagHelper功能,咱们已经在TagHelper中讲解过了web

注意,在本例中,咱们只引用了BookStore命名空间,并无引用BookStore.Controllers命名空间,因此咱们在任何视图中,都没法访问HomeController类(也不能以Controllers.HomeController的形式进行访问),但愿微软之后能加以改进。async

获取IP相关信息

要获取用户访问者的IP地址相关信息,能够利用依赖注入,获取IHttpConnectionFeature的实例,从该实例上能够获取IP地址的相关信息,实例以下:post

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端口

相似地,你也能够经过IHttpRequestFeatureIHttpResponseFeatureIHttpClientCertificateFeatureIWebSocketAcceptContext等接口,获取相关的实例,从而使用该实例上的特性,上述接口都在命名空间Microsoft.AspNet.HttpFeature的下面。code

文件上传

MVC6在文件上传方面,给了新的改进处理,举例以下:orm

<form method="post" enctype="multipart/form-data">
    <input type="file" name="files" id="files" multiple />
<input type="submit" value="submit" />
</form>

咱们在前端页面定义上述上传表单,在接收可使用MVC6中的新文件类型IFormFile,实例以下:htm

[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系列blog

相关文章
相关标签/搜索