当前位置: 移动技术网 > IT编程>开发语言>.net > 解读ASP.NET 5 & MVC6系列教程(17):MVC中的其他新特性

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

runningman综艺,高楼爆破2无敌版,超星舰队粤语

(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"

上述代码表示,引用bookstoremicrosoft.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端口

类似地,你也可以通过ihttprequestfeatureihttpresponsefeatureihttpclientcertificatefeatureiwebsocketacceptcontext等接口,获取相关的实例,从而使用该实例上的特性,上述接口都在命名空间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
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网