源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-03-09 07:06 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:解读ASP.NET 5 & MVC6系列教程(17):MVC中的其他新特性
[b](GlobalImport全局导入功能)[/b] 默认新建立的MVC程序中,在Views目录下,新增加了一个[code]_GlobalImport.cshtml[/code]文件和[code]_ViewStart.cshtml[/code]平级,该文件的功能类似于之前Views目录下的web.config文件,之前我们在该文件中经常设置全局导入的命名空间,以避免在每个view文件中重复使用[code]@using xx.xx[/code]语句。 默认的示例如下:
@using BookStore
@using Microsoft.Framework.OptionsModel
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
上述代码表示,引用[code]BookStore[/code]和[code]Microsoft.Framework.OptionsModel[/code]命名空间,以及[code]Microsoft.AspNet.Mvc.TagHelpers[/code]程序集下的所有命名空间。 关于addTagHelper功能,我们已经在TagHelper中讲解过了 注意,在本例中,我们只引用了[code]BookStore[/code]命名空间,并没有引用[code]BookStore.Controllers[/code]命名空间,所以我们在任何视图中,都无法访问[code]HomeController[/code]类(也不能以[code]Controllers.HomeController[/code]的形式进行访问),希望微软以后能加以改进。 [b]获取IP相关信息[/b] 要获取用户访问者的IP地址相关信息,可以利用依赖注入,获取[code]IHttpConnectionFeature[/code]的实例,从该实例上可以获取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端口
类似地,你也可以通过[code]IHttpRequestFeature[/code]、[code]IHttpResponseFeature[/code]、[code]IHttpClientCertificateFeature[/code]、 [code]IWebSocketAcceptContext[/code]等接口,获取相关的实例,从而使用该实例上的特性,上述接口都在命名空间[code]Microsoft.AspNet.HttpFeature[/code]的下面。 [b]文件上传[/b] MVC6在文件上传方面,给了新的改进处理,举例如下:
<form method="post" enctype="multipart/form-data">
  <input type="file" name="files" id="files" multiple />
<input type="submit" value="submit" />
</form>
我们在前端页面定义上述上传表单,在接收可以使用MVC6中的新文件类型[code]IFormFile[/code],实例如下:
[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
}
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部