ASP.NET MVC 的 ValidateAntiForgeryToken機制

這是ASP.NET MVC 為防止 CSRF (Cross-Site Request Forgery) 跨站偽造請求的攻擊的設計,作法如下:

Step01. 在 Action 加上 [ValidateAntiForgeryToken] 標籤

[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{ 
    ...
    return View();
}

Step02. 在 cshtml 就必須要加上 @Html.AntiForgeryToken(),否則會出錯

@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
    @Html.AntiForgeryToken()
}

使用 gtag.js 增加按鈕事件

常常被客戶要求 Google Analytics 要設定按鈕事件,所以先筆記起來一下


<a class="doc-dl xls" title="下載 Excel" href="/TC/OPENDATA/Comm1_MEMBER.xls">Excel</a>
<a class="doc-dl pdf" title="下載 PDF" href="/TC/OPENDATA/Comm1_MEMBER.pdf">pdf</a>
<a class="doc-dl csv" title="下載 CSV" href="TC/OPENDATA/Comm1_MEMBER.csv">csv</a>
<a class="doc-dl xml" title="下載 XML" href="/TC/OPENDATA/Comm1_MEMBER.xml">xml</a>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=追蹤碼"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }
    gtag('js', new Date());
    gtag('config', '追蹤碼');

    function download_tracking(e) {
        var addressValue = e.toString();
        addressValue = addressValue.replace('網站domain', '');
        gtag('event', '下載', {
           'event_category': 'OpenData',
           'event_label': addressValue
    });
}
</script>

ASP.NET MVC 使用 DI Framework – Autofac

Step01. 安裝 Autofac

Step02. 安裝 Autofac.Mvc5

Step03. 在 App_Start 加入 AutofacConfig.cs

public class AutofacConfig
{
    public static void Bootstrapper()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        builder.RegisterType<TimidoColorDB>()
        .As<ITimidoColorDB>()
        .InstancePerRequest();

        var services = Assembly.Load("TimidoColor.Services");
        builder.RegisterAssemblyTypes(services).AsImplementedInterfaces();

        var helper = Assembly.Load("TimidoColor.Core");
        builder.RegisterAssemblyTypes(helper).AsImplementedInterfaces();

        builder.RegisterFilterProvider();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

Step04. Global.asax 加入 AutofacConfig.Bootstrapper();

 

protected void Application_Start()
{
    AutofacConfig.Bootstrapper();

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

使用 EntityFramework Reverse POCO Generator

如果使用ADO.NET實體資料模型來產生資料庫的Model,你會發現Web.config 的資料連線有點小複雜,多了 metadata 的一些宣告,如

  <connectionStrings><add name="ProjectDBEntities" connectionString="metadata=res://*/AllModels.csdl|res://*/AllModels.ssdl|res://*/AllModels.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDb)\MSSQLLocalDB;initial catalog=ProjectDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

如用EntityFramework Reverse POCO Generator,則可用一般的連線字串即可

 <connectionStrings>
<add name="ProjectDBEntity" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;initial catalog=ProjectDB;persist security info=True; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

首先到 Visual Studio Market Place
下載安裝 EntityFramework Reverse POCO Generator
閱讀全文〈使用 EntityFramework Reverse POCO Generator〉

解決 ASP.NET MVC 的 HtmlHelper 找不到的錯誤

這應該是剛開始學ASP.NET MVC 常犯的錯誤,一般我們會新增一個資料夾”Helpers”來放 HtmlHelper的程式,如在資料夾新增一個class,如:HMTLHelperExtensions.cs。

using System;
using System.Web.Mvc;

namespace DemoCustomIndentity.Helpers
{
    public static class HMTLHelperExtensions
    {
       public static string IsSelected(this HtmlHelper html, string controller = null, string action = null, string cssClass = null)
       {

          if (String.IsNullOrEmpty(cssClass))
          cssClass = "active";

          string currentAction = (string)html.ViewContext.RouteData.Values["action"];
          string currentController = (string)html.ViewContext.RouteData.Values["controller"];

          if (String.IsNullOrEmpty(controller))
          controller = currentController;

         if (String.IsNullOrEmpty(action))
         action = currentAction;

         return controller == currentController && action == currentAction ?
         cssClass : String.Empty;
       }

    public static string PageClass(this HtmlHelper html)
    {
       string currentAction = (string)html.ViewContext.RouteData.Values["action"];
       return currentAction;
     }
   }
}

閱讀全文〈解決 ASP.NET MVC 的 HtmlHelper 找不到的錯誤〉