首页
归档
留言
友链
广告合作
壁纸
更多
美女主播
Search
1
博瑞GE车机升级/降级
5,610 阅读
2
Mac打印机设置黑白打印
4,950 阅读
3
修改elementUI中el-table树形结构图标
4,895 阅读
4
Mac客户端添加腾讯企业邮箱方法
4,674 阅读
5
intelliJ Idea 2022.2.X破解
4,357 阅读
后端开发
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
登录
/
注册
Search
标签搜索
Spring Boot
Java
Vue
Spring Cloud
Mac
MyBatis
WordPress
MacOS
asp.net
Element UI
Nacos
.Net
Spring Cloud Alibaba
MySQL
Mybatis-Plus
Typecho
jQuery
Java Script
IntelliJ IDEA
微信小程序
Laughing
累计撰写
627
篇文章
累计收到
1,421
条评论
首页
栏目
后端开发
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
页面
归档
留言
友链
广告合作
壁纸
美女主播
搜索到
224
篇与
的结果
2018-03-10
由于先前已在此页中指定了另一种语言(或者由 CodeFile 特性暗示),因此无法使用“javascript”。
其实我没学过Asp.Net,之前一直都是html的,最近公司一直再用aspx的东西,所以特地学习以下。错误代码如下<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script language="javascript" type="text/javascript" runat="server"> function btnRed_onClick() { form1.style.backgroundColor = "Red"; } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" value="red" onclick="return btnRed_onClick()" /> </div> </form> </body> </html> 解决方法去掉<script language="javascript" type="text/javascript" runat="server">中的runat="server"因为<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>指定了在服务器端执行的是C#语言,<script language="javascript" type="text/javascript" runat="server">想在服务器端执行,显然是不行的。
2018年03月10日
1,113 阅读
0 评论
0 点赞
2018-03-09
C#创建IIS站点
利用IIS7自带类库管理IIS现在变的更强大更方便,而完全可以不需要用DirecotryEntry这个类了(网上很多.net管理iis6.0的文章都用到了DirecotryEntry这个类 ),Microsoft.Web.Administration.dll位于IIS的目录(%WinDir%\System32\InetSrv)下,使用时需要引用,它基本上可以管理IIS7的各项配置。这个类库的主体结构如下:前端代码 <%@ Page Title="IIS管理" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Manager.aspx.cs" Inherits="IISManager.Ide.Net.Cn.Manager" %> <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> <h2><%:Page.Title %></h2> <asp:Panel CssClass="panel panel-default" runat="server"> <div class="panel-body"> <asp:Label runat="server" CssClass="control-label">网站IP</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtIP" ClientIDMode="Static" ToolTip="网站名称">localhost</asp:TextBox> <br /> <asp:Label runat="server" CssClass="control-label">网站名称</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtSiteName" ClientIDMode="Static" ToolTip="网站名称">test</asp:TextBox> <br /> <asp:Label runat="server" CssClass="control-label">物理路径</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtPath" ClientIDMode="Static" ToolTip="网站路径">c:\test</asp:TextBox> <br /> <asp:Label runat="server" CssClass="control-label">端口</asp:Label><asp:TextBox CssClass="form-control" Width="100%" runat="server" ID="txtPort" ClientIDMode="Static" ToolTip="网站端口">1234</asp:TextBox> <br /> <asp:Button ID="btnAdd" EnableViewState="false" UseSubmitBehavior="false" runat="server" Text="提交" CssClass="btn btn-default" OnClick="btnAdd_Click"></asp:Button> </div> </asp:Panel> </asp:Content>后台代码using Microsoft.Web.Administration; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace IISManager.Ide.Net.Cn { public partial class Manager : Page { string ip = string.Empty; protected void Page_Load(object sender, EventArgs e) { if (!ConfigurationManager.AppSettings.AllKeys.Contains("IP")) { Response.Write("<script>alert('config文件配置不正确')</script>"); Response.Write(" <script> window.close(); </script> "); return; } ip = ConfigurationManager.AppSettings["IP"]; if (string.IsNullOrEmpty(ip)) { Response.Write("<script>alert('请配置IP地址')</script>"); Response.Write(" <script> window.close(); </script> "); return; } } protected void btnAdd_Click(object sender, EventArgs e) { try { string siteName = txtSiteName.Text.Trim(); int port = Convert.ToInt32(txtPort.Text.Trim()); string path = txtPath.Text.Trim(); FileInfo fi = new FileInfo(path); if ((fi.Attributes & FileAttributes.Directory) != 0) { } else { Response.Write("<script>alert('文件路径无效')</script>"); } ServerManager sm = ServerManager.OpenRemote(this.txtIP.Text.Trim()); //创建应用程序池 //先检测是否存在,如果存在不进行操作 //如果创建的应用程序池已经存在,系统不会进行创建 ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == siteName); if (appPool != null) { sm.ApplicationPools.Remove(appPool); } appPool = sm.ApplicationPools.Add(siteName); appPool.AutoStart = true;//是否自动启动,true代表创建完成后自动启动 appPool.Enable32BitAppOnWin64 = false;//启动32位支持 appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;//托管管道模式Integrated = 0, Classic = 1 appPool.ManagedRuntimeVersion = "v4.0";//版本 appPool.QueueLength = 10000;//队列长度,如果操作限制将显示503 appPool.Recycling.PeriodicRestart.Time = new TimeSpan(0, 5, 0);//固定回收时间 appPool.ProcessModel.IdleTimeout = new TimeSpan(0, 5, 0);//5分钟闲置超时 appPool.ProcessModel.MaxProcesses = 1;//最大进程数 appPool.ProcessModel.PingingEnabled = true;//是否允许ping appPool.ProcessModel.PingInterval = new TimeSpan(0, 0, 40);//ping间隔 appPool.ProcessModel.PingResponseTime = new TimeSpan(0, 0, 10);//ping最大相应时间 10秒 appPool.ProcessModel.ShutdownTimeLimit = new TimeSpan(0, 0, 50);//关闭时间限制 appPool.ProcessModel.StartupTimeLimit = new TimeSpan(0, 0, 50);//启动时间限制 //创建站点 Site site = sm.Sites.FirstOrDefault(x => x.Name == siteName); if (site != null) { sm.Sites.Remove(site); } site = sm.Sites.Add(siteName, path, port); site.ServerAutoStart = true;//自动启动 Application root = site.Applications["/"]; root.ApplicationPoolName = appPool.Name;//设置应用程序池 site.Bindings[0].EndPoint.Port = port;//终点端口号 site.Limits.MaxBandwidth = 2000000;//最大带宽 site.Limits.MaxConnections = 1000;//最大连接数 site.LogFile.Directory = path + "\\log";//日志文件路径 site.LogFile.Enabled = true;//开启日志 site.LogFile.LogExtFileFlags = LogExtFileFlags.Date;//日志文件形式 site.LogFile.LogFormat = LogFormat.Custom;//日志格式 site.LogFile.Period = LoggingRolloverPeriod.Hourly;//日志文件记录时间间隔 site.LogFile.TruncateSize = 1048577;//日志文件截取大小 site.TraceFailedRequestsLogging.MaxLogFiles = 100;//失败请求最大跟踪日志数量 site.TraceFailedRequestsLogging.Directory = path + "\\tracelog";//失败请求日志路径 site.TraceFailedRequestsLogging.Enabled = true;//启用失败请求跟踪 //site.SetAttributeValue("preloadEnabled", true);//启用预加载 sm.CommitChanges(); Response.Write("<script>alert('创建成功')</script>"); } catch (Exception ex) { Response.Write("<script>alert('创建失败,请检查输入先是否正确')</script>"); } } } }配置文件<?xml version="1.0"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <!-- 有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。 可在 <httpRuntime> 标记上设置以下特性。 <system.Web> <httpRuntime targetFramework="4.6.1" /> </system.Web> --> <appSettings> <add key="SiteName" value="IIS管理系统"/> <add key="IP" value="58.87.77.174"/> </appSettings> <system.web> <identity impersonate="true" userName="administrator" password="123456"/> <compilation debug="true" targetFramework="4.6.1"/> <httpRuntime/> <pages controlRenderingCompatibilityVersion="4.0"> <namespaces> <add namespace="System.Web.Optimization"/> </namespaces> <controls> <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/> </controls> </pages> <httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/> </httpModules> </system.web> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/> </dependentAssembly> </assemblyBinding> </runtime> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="ApplicationInsightsWebTracking"/> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/> </modules> </system.webServer> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/> </compilers> </system.codedom> </configuration>温馨提示配置文件主要是identity节点,配置登陆用户
2018年03月09日
1,341 阅读
0 评论
1 点赞
2018-01-22
jspSmartUpload使用
jspSmartUpload官方已经停止更新jspSmartUpload可以轻松实现文件的上传、下载功能,对于文件上传类型限制控制也非常灵活IntelliJ IDE引用jar包右键项目,选择Open Module Setting或者使用⌘+↓快捷键,在打开的界面,左侧选择Library,然后点击➕,选中对应的jar,引入后点击确定按钮引入完成后,查看项目目录应该如下:使用smartupload实现简单的文件上传功能
2018年01月22日
1,445 阅读
0 评论
1 点赞
2017-12-24
Ubuntu各版本下安装DotNetCore2.0
最近看了一下Linux安装DotNetCore的方法,发现微软官网上面的教程各种问题,还不如GitHub上面的。所以特地整理了一下Ubuntu下面的安装命令,作为日后的记录。温馨提示如果之前有安装的预览版的DotNetCore,需要先进行卸载,命令如下sudo apt remove dotnet-dev-2.0.0-preview2-006497 Ubuntu 17.04curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-zesty-prod zesty main" > /etc/apt/sources.list.d/dotnetdev.list' Ubuntu 16.04curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main" > /etc/apt/sources.list.d/dotnetdev.list' Ubuntu 14.04curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-trusty-prod trusty main" > /etc/apt/sources.list.d/dotnetdev.list'
2017年12月24日
1,383 阅读
2 评论
1 点赞
2017-12-08
ASP.NET MVC客户端及服务端验证
在mvc中使用表单进行数据提交时,数据验证分为服务器端验证和客户端验证;我们可以通过使用HtmlHelper中的方法及在页面中引用js库对Model的属性的数据注解(System.ComponentModel.DataAnnotations命名空间下的一组类)进行解析,实现前端、后端的数据验证;其实客户端验证也是调用的jquery.validate.js,我个人觉得,通过数据注解,服务端的验证确实能够方便不少,但是客户端的验证,感觉还不如直接用jquery.validate来的方便。数据注解以及微软内置的验证这里就不多介绍了,这里我们主要介绍一下如何实现服务端和客户端自定义验证前期准备代码,实体类、控制器、视图实体类using me.lisen.MVC.Public; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace me.lisen.MVC.Models { public class Product { [Key] public string ID { get; set; } [Display(Name="产品名称")] [Required(ErrorMessage ="请输入产品名称")] [StringLength(2,ErrorMessage ="最多输入两个字符")] public string Name { get; set; } [Display(Name ="价格")] [Required(ErrorMessage ="请输入价格")] [PriceValid(MinPrice =20.00,ErrorMessage ="价格不能低于20元")] public Decimal Price { get; set; } } }控制器using me.lisen.MVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace me.lisen.MVC.Controllers { public class ProductController : Controller { // GET: Product public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Product product) { if (ModelState.IsValid) { return RedirectToAction("Create"); } return View(); } } }视图@model me.lisen.MVC.Models.Product @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Product</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div>服务端验证实现自定义的服务端验证非常简单,我们只需要继承ValidationAttribute类,然后重写IsValid()方法即可using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace me.lisen.MVC.Public { public class PriceValid:ValidationAttribute { public double MinPrice { get; set; } public override bool IsValid(object value) { if (value == null) { return true; } var price = Convert.ToDouble(value); if(price < MinPrice) { return false; } return true; } } }返回true或false代表验证是否通过。客户端验证自定义客户端验证就比较繁琐了,我们需要实现IClientValidatable接口的, public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context )方法,然后在方法中定义传递给js的方法名以及方法参数。实现接口IClientValidatableusing System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace me.lisen.MVC.Public { public class PriceValid:ValidationAttribute,IClientValidatable { public double MinPrice { get; set; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule(); rule.ErrorMessage = metadata.GetDisplayName() + "不能小于系统限制"; rule.ValidationParameters.Add("minprice", MinPrice); rule.ValidationType = "price"; yield return rule; } public override bool IsValid(object value) { if (value == null) { return true; } var price = Convert.ToDouble(value); if(price < MinPrice) { return false; } return true; } } }添加js文件/* 第一个参数是服务端ValidationType值 第二个参数必须是ValidationParameters.Add()的值 */ $.validator.unobtrusive.adapters.addSingleVal("price", "minprice"); $.validator.addMethod("price", function (value, element, param) { if (value) { var inputValue = parseInt(value, 10); var validateValue = parseInt(param, 10); if (inputValue < validateValue) { return false; } } return true; });页面引入js文件
2017年12月08日
1,505 阅读
2 评论
2 点赞
2017-12-06
asp.net mvc area区域
Area可以在原来的MVC项目中开辟一块单独的区域放置功能模块。独立出来的区域可以包含专用的M-V-C功能,也可以包含独立的路由和视图引擎。这里我们主要针对区域的创建以及区域相互调用还有路由限制进行简答的说明。创建MVC项目后,会包含一个HomeController,这里我们为了演示,在建立一个名为Home的区域。路由冲突Area创建完成后,如果我们直接访问,会提示找到多个与名为“Home”的控制器匹配的类型。如果为此请求(“{controller}/{action}/{id}”)提供服务的路由没有指定命名空间以搜索与此请求相匹配的控制器,则会发生这种情况。如果是这样,请通过调用带有 'namespaces' 参数的 "MapRoute" 方法的重载来注册此路由。出现这个的原因,是我们区域中的路由跟外部HomeController的路由发生了冲突,为了解决这个问题,我们必须对路由匹配规则进行限制。路由限制路由限制的方式由很多种,可以限制controller或者action等等,这里我们通过限制HomeController的命名空间来进行限制。打开App_Start文件夹,找到RouteConfig.cs文件,修改RegisterRoutes方法如下public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "me.lisen.WebUI.Controllers" } ); }修改完成后,我们再次打开运行项目发现能正常打开了通过routedebugger,我们可以看到首页匹配到了Home/Index上面区域相互访问创建完区域之后,我们可以外部需要访问内部区域,或者内部访问外部区域,这个可以通过便签助手,增加area属性解决。比如我们外部需要访问内部Home区域,只需要在标签助手在区域即可<a href="@Url.Action("Index","Home",new { area="Home"})">前往内部首页</a> 如果需要内部区域访问外部区域,将area设置成""即可<a href="@Url.Action("Index","Home",new { area=""})">前往外部首页</a> 温馨提示统一区域内相互访问时,不需要加area属性。
2017年12月06日
1,479 阅读
0 评论
1 点赞
2017-12-06
ASP.NET MVC使用Ninject
本文主要介绍的是通过构造函数加上配置文件的形式,完成注入工作。当然网上很多人也说不依赖XML是Ninject的一大优点,这里我也仅仅是进行演示,大家可以通过bind-to的方式直接进行的。安装NugetNuget的安装这里就不多介绍了,本文使用的Nuget包如下Ninject Ninject.Extensions.Xml温馨提示如果使用XML加载的方式,必须添加Ninject.Extensions.Xml包Ninject注入我们继承DefaultControllerFactory创建NinjectControllerFactory,代码如下using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ninject; using System.Web.Mvc; using me.lisen.Db.CustomerDb; using System.Web.Routing; using System.Web; namespace me.lisen.Util.Loc { public class NinjectControllerFactory : DefaultControllerFactory { IKernel kernel; public NinjectControllerFactory() { kernel = new StandardKernel(); AddBinding(); } protected override IController GetControllerInstance(RequestContext context,Type controllerType) { return controllerType == null ? null : (IController)kernel.Get(controllerType); } public void AddBinding() { kernel.Load(HttpContext.Current.Server.MapPath(".")+"\\XmlConfig\\Ninject.xml"); //kernel.Bind<ICustomerDb>().To<CustomerDb>(); } } }创建接口和实现类,具体代码如下using me.lisen.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace me.lisen.Db.CustomerDb { public interface ICustomerDb { List<Customer> GetCustomers(); List<Customer> GetCustomers(string whereKey, string whereValue); } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using me.lisen.Models; using Ninject; using System.Data.Entity; namespace me.lisen.Db.CustomerDb { public class CustomerDb : ICustomerDb { private readonly NorthwindContext context; [Inject] public CustomerDb() { context = new NorthwindContext(); } public List<Customer> GetCustomers() { return context.Customers.ToList<Customer>(); } public List<Customer> GetCustomers(string whereKey, string whereValue) { return context.Customers.Where(e => e.ContactName == whereValue).ToList<Customer>(); } } }修改Global.asax中Application_Start方法,添加以下代码ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); 使用我们通过构造函数调用,修改控制器构造函数private readonly ICustomerDb customerDb; public CustomerController(ICustomerDb customerDb) { this.customerDb = customerDb; }xml文件配置<module name="Db"> <bind service="me.lisen.Db.CustomerDb.ICustomerDb,me.lisen.Db" to="me.lisen.Db.CustomerDb.CustomerDb,me.lisen.Db"></bind> </module>
2017年12月06日
1,384 阅读
0 评论
1 点赞
2017-12-04
asp.net core生成html页面
为了缓解服务器的压力,我们可以将一些不经常更新的页面生成html页面,然后保存到服务器,页面进行查询时,我们先查找html是否存在,如果存在,我们直接返回html页面,否则就生成对应的html页面。这里我们通过动作过滤器ActionFilterAttribute实现。定义属性using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cc.lisen.Public.Attribute { /// <summary> /// 实现伪静态 /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class StaticFileHandlerFilterAttribute : ActionFilterAttribute { public string Key { get; set; } /// <summary> /// 动作执行后 /// </summary> /// <param name="context"></param> public override void OnActionExecuted(ActionExecutedContext context) { //获取结果 IActionResult actionResult = context.Result; //判断结果是否是一个ViewResult if (actionResult is ViewResult) { ViewResult viewResult = actionResult as ViewResult; //下面的代码就是执行这个ViewResult,并把结果的html内容放到一个StringBuiler对象中 var services = context.HttpContext.RequestServices; var executor = services.GetRequiredService<ViewResultExecutor>(); var option = services.GetRequiredService<IOptions<MvcViewOptions>>(); var result = executor.FindView(context, viewResult); result.EnsureSuccessful(originalLocations: null); var view = result.View; StringBuilder builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { var viewContext = new ViewContext( context, view, viewResult.ViewData, viewResult.TempData, writer, option.Value.HtmlHelperOptions); view.RenderAsync(viewContext).GetAwaiter().GetResult(); //这句一定要调用,否则内容就会是空的 writer.Flush(); } //按照规则生成静态文件名称 string controllerName = context.RouteData.Values["controller"].ToString().ToLower(); string actionName = context.RouteData.Values["action"].ToString().ToLower(); string id = context.RouteData.Values.ContainsKey(Key) ? context.RouteData.Values[Key].ToString() : ""; if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(Key)) { id = context.HttpContext.Request.Query[Key]; } string devicedir = Path.Combine(AppContext.BaseDirectory, "wwwroot"); if (!Directory.Exists(devicedir)) { Directory.CreateDirectory(devicedir); } //写入文件 string filePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", controllerName + "-" + actionName + (string.IsNullOrEmpty(id) ? "" : ("-" + id)) + ".html"); using (FileStream fs = File.Open(filePath, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { sw.Write(builder.ToString()); } } //输出当前的结果 ContentResult contentresult = new ContentResult(); contentresult.Content = builder.ToString(); contentresult.ContentType = "text/html"; context.Result = contentresult; } } /// <summary> /// 动作执行前 /// </summary> /// <param name="context"></param> public override void OnActionExecuting(ActionExecutingContext context) { //按照一定的规则生成静态文件的名称,这里是按照area+"-"+controller+"-"+action+key规则生成 string controllerName = context.RouteData.Values["controller"].ToString().ToLower(); string actionName = context.RouteData.Values["action"].ToString().ToLower(); //这里的Key默认等于id,当然我们可以配置不同的Key名称 string id = context.RouteData.Values.ContainsKey(Key) ? context.RouteData.Values[Key].ToString() : ""; if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(Key)) { id = context.HttpContext.Request.Query[Key]; } string filePath = Path.Combine(AppContext.BaseDirectory, "wwwroot", controllerName + "-" + actionName + (string.IsNullOrEmpty(id) ? "" : ("-" + id)) + ".html"); //判断文件是否存在 if (File.Exists(filePath)) { FileInfo fileInfo = new FileInfo(filePath); TimeSpan timeSpan = DateTime.Now - fileInfo.CreationTime; if (timeSpan.TotalDays <= 1) { //如果存在,直接读取文件 using (FileStream fs = File.Open(filePath, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { //通过contentresult返回文件内容 ContentResult contentresult = new ContentResult(); contentresult.Content = sr.ReadToEnd(); contentresult.ContentType = "text/html"; context.Result = contentresult; } } } } } } }使用我们可以通过将属性设置到类或者方法上面来使用using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using cc.lisen.Models.Entity; using cc.lisen.Public.ArticleHelper; using cc.lisen.Public.MenuHelper; using Microsoft.AspNetCore.Authorization; using cc.lisen.Public.Attribute; namespace cc.lisen.Controllers { [StaticFileHandlerFilter(Key = "id")] public class ArticleController : BaseController { private readonly IArticleHelper articleHelper; public ArticleController(IArticleHelper articleHelper, IMenuHelper menuHelper) : base(menuHelper) { this.articleHelper = articleHelper; } // GET: Article public ActionResult Index() { List<Article> list = articleHelper.GetList(); return View(list); } // GET: Article/Details/5 [StaticFileHandlerFilter(Key = "id")] public ActionResult Details(string id) { Article article = articleHelper.GetArticle(id); return View(article); } // GET: Article/Create [Authorize(Roles = "admin")] public ActionResult Create() { return View(); } // POST: Article/Create [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "admin")] public ActionResult Create(Article article) { try { articleHelper.InsertArticle(article); return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: Article/Edit/5 [Authorize(Roles = "admin")] public ActionResult Edit(string id) { Article article = articleHelper.GetArticle(id); return View(article); } // POST: Article/Edit/5 [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "admin")] public ActionResult Edit(string id, Article article) { try { // TODO: Add update logic here articleHelper.EditArticle(article); return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: Article/Delete/5 [Authorize(Roles = "admin")] public ActionResult Delete(string id) { if (articleHelper.DeleteArticle(id)) { ViewBag.IsDeleted = "删除成功"; } else { ViewBag.IsDeleted = "删除失败"; } return View(); } // POST: Article/Delete/5 [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "admin")] public ActionResult Delete(string id, IFormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction(nameof(Index)); } catch { return View(); } } } }查看结果我们查看wwroot页面,可以查看生成的html页面
2017年12月04日
1,437 阅读
0 评论
2 点赞
2017-11-29
asp.net core中bootstrap-table无法获取返回的Json数据
之前在ASP.NET Core下面,通过bootstrap-table也展示过数据,当时也是在controller中直接返回了Json对象,当时没有任何问题,但是今天测试的时候,发现返回的数据不能展示了,所有的数据都变成了 -,其实就是数据有问题,但是查看返回的Json数据的时候,Json数据格式也没有任何问题。处理Json返回的数据更多调试发现,Json对象还有一个JsonSerializerSettings参数的重载函数,然后直接实例化了一个JsonSerializerSettings对象,然后返回Json就可以了,具体如下var rows = productHelper.GetProductPager(limit, offset); int total = rows.Count(); JsonSerializerSettings settings = new JsonSerializerSettings(); //settings.MaxDepth = 50; //settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //设置不处理循环引用 //转成Json格式 return Json(new { total = total, rows = rows }, settings); //return Json(new { total = total, rows = rows });
2017年11月29日
1,537 阅读
0 评论
22 点赞
2017-11-26
DotNet Core部署iis提示The application process started but failed to listen on the configured port
今天将一个DotNetCore网站部署到IIS的时候,系统提示The application process started but failed to listen on the configured port首先提示这个错误的,肯定是已经安装了Windows Server Hosting,如果没有安装Windows Server Hosting 的话,报错的信息不是这个,但是既然安装了Windows Server Hosting,为什么还会提示这个错误呢,其实导致这个错误的原因非常简单:就是安装完Windows Server Hosting没有重启IIS.重启IIS时,只重启了当前网站。所以解决办法也非常简单安装完Windows Server Hosting后一定要重启IIS,大家可以使用 iisreset命令重启
2017年11月26日
1,684 阅读
1 评论
0 点赞
2017-11-25
ASP.NET Core使用Redis
Redis是优秀的缓存组件,我们在DotNetCore中也能够很方便的使用。本文主要介绍在虚拟机安装Window Server作为缓存服务器进行简单使用的方法。使用准备为了使用Redis,我们需要一个缓存服务器,这里我们所有的东西都是通过Nuget的方式进行安装的。需要注意的是,Redis官方没有Win版本的,但是我们可以使用微软第三方的我们首先需要安装一下的Nuget包Microsoft.AspNetCore.Session Microsoft.AspNetCore.Http.Extensions Microsoft.Extensions.Caching.Redis Redis-64其中Redis位于C:\Users\Administrator.nuget\packages\redis-64将Redis-64文件夹拷贝到服务器,然后打开\3.0.503\tools\redis-server.exe 开启Redis
2017年11月25日
1,461 阅读
0 评论
2 点赞
2017-11-25
ASP.NET Core ISession找不到SetString方法
不得不感叹一下,现在ASP.NET Core的资料实在是太少了,官网的文档看着也混乱。有时候遇到点问题都找不到解决方案,网上的文章也基本是一人发表,全网来抄。DoNetCore默认的Session只能写入byte数组,为了能够调用SetString()方法,我们还需要安装如下的Nuget包Microsoft.AspNetCore.Http.Extensions这个当时郁闷了好久,就是找不到SetString()方法,大家如果碰到的,也看一下是不是缺少包
2017年11月25日
1,610 阅读
2 评论
2 点赞
1
...
16
17
18
19