【操做記錄】Asp.Net Core 的一些基本操做或屬性

用於記錄在項目中使用到的方法、屬性、操做,持續更新中

.net core 開源地址html

圖片上傳:

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() <= 0) {
           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[0].CopyToAsync(stream);
          }
             result.Data = strpath;
       }
       else
       {
          result.Msg = "圖片格式錯誤";
       }
   return Json(result);
}

 ps:獲取上傳文件信息 可以使用  IFormFileCollection 或者 Request.Form.Files來獲取。git

.net core 2.0發佈後,不把 view 文件編譯打包,修改 csproj文件中 PropertyGroup 節點,配置節MvcRazorCompileOnPublish設爲false就行github

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

發佈如圖所示session

 Drawing繪製圖片,官方包:

System.Drawing.Common

靜態文件的使用

在項目中靜態文件的使用須要在Startup中的Configure方法中增長:mvc

//使用靜態文件
app.UseStaticFiles();

這樣就能夠訪問全部wwwroot目錄下的靜態文件,可是若想訪問Views/Menu/Index.js文件,還須要在Configure方法中增長:app

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

在mvc中加載其餘頁面到當前頁面:async

@Html.Partial("_Edit")

@RenderSection 詳解:http://www.cnblogs.com/Joetao/articles/4191682.htmlide

session過時驗證:spa

 /// <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);
        }
    }
相關文章
相關標籤/搜索