【日常操作记录】Asp.Net Core 的一些基本操作或属性

时间:2024-01-04 08:55:44

用于记录在项目中使用到的方法、属性、操作,持续更新中

.net core 开源地址

图片上传:

public async Task<IActionResult> Upload([FromServices]IHostingEnvironment environment)
{
var result = new BaseResult();
string path = string.Empty;
var files = Request.Form.Files;
if (files == null || files.Count() <= ) {
result.Msg = "请选择上传的文件。";
return Json(result);
}
//格式限制
var allowType = new string[] { "image/jpg", "image/png" , "image/jpeg" };
if (files.Any(c => allowType.Contains(c.ContentType)))
{
string strpath = Path.Combine("images", DateTime.Now.ToString("MMddHHmmss"));
path = Path.Combine(environment.WebRootPath, strpath);
using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
await files[].CopyToAsync(stream);
}
result.Data = strpath;
}
else
{
result.Msg = "图片格式错误";
}
return Json(result);
}

ps:获取上传文件信息 可使用  IFormFileCollection 或者 Request.Form.Files来获取。

.net core 2.0发布后,不把 view 文件编译打包,修改 csproj文件中 PropertyGroup 节点,配置节MvcRazorCompileOnPublish设为false就行

 <PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
</PropertyGroup>

发布如图所示

【日常操作记录】Asp.Net Core 的一些基本操作或属性

Drawing绘制图片,官方包:

System.Drawing.Common

静态文件的使用

在项目中静态文件的使用需要在Startup中的Configure方法中增加:

//使用静态文件
app.UseStaticFiles();

这样就可以访问所有wwwroot目录下的静态文件,但是若想访问Views/Menu/Index.js文件,还需要在Configure方法中增加:

app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory())
});
//在页面的引用方式
@section scripts{
<script src="~/Views/Department/Index.js"></script>
}

在mvc中加载其他页面到当前页面:

@Html.Partial("_Edit")

@RenderSection 详解:http://www.cnblogs.com/Joetao/articles/4191682.html

session过期验证:

 /// <summary>
/// 拦截控制器
/// </summary>
public class InterceptController : Controller
{
public override void OnActionExecuted(ActionExecutedContext context)
{
byte[] result;
//获取session的值
context.HttpContext.Session.TryGetValue("UserInfo", out result);
if (result==null)
{
//重定向到登录页面
context.Result = new RedirectResult("/Login");
}
base.OnActionExecuted(context);
}
}