顯示具有 MVC 標籤的文章。 顯示所有文章
顯示具有 MVC 標籤的文章。 顯示所有文章

2020年1月16日 星期四

[MVC] 自訂Authentication

複習一下 :

    public class CustomAuthenticationFilter : IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true))
            {
                return;
            }

            if (filterContext.Principal.Identity.IsAuthenticated && filterContext.Principal.Identity is FormsIdentity)
            {
             
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                {"controller","Default"},
                {"action","Logon"},
                {"returnUrl",filterContext.HttpContext.Request.RawUrl }
            });
            }
            //or do something , add challenge to response

        }
    }


參考:https://dotblogs.com.tw/libtong/2017/10/03/105527

2019年3月20日 星期三

[MVC] 遇到cshtml 的 linq 無法順利解析 (出現紅色毛毛蟲)









有時cshtml頁面居然出現以上紅色毛毛蟲的現象

編譯正常也沒問題,但就是非常惱人,一鍵完成選單也無法使用

解法 :

在webconfig 內加入以下內容,然後編譯後再重新開啟cshtml即可正常囉

      <assemblies>
        <add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
        <add assembly="System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
        <add assembly="Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
        <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>



2017年4月17日 星期一

[mvc] 加入多國語系


簡易流程 : 簡單說就是利用cookie紀錄瀏覽器的預設語系,然後在server端切換對應的語系檔(.resource)
1.在controller 加入切換語系的action

public ActionResult ChangeLang(String langCode, String bakCtrl, String bakAct)
      {
          //use Cookies save lang code
          HttpCookie LangCookie = Request.Cookies["lang"];
 
          if (LangCookie == null)
          {
              LangCookie = new HttpCookie("lang");
          }
 
          LangCookie.Value = langCode;
          LangCookie.Expires.AddDays(1);
          Response.Cookies.Add(LangCookie);
 
          if (String.IsNullOrEmpty(bakCtrl) || String.IsNullOrEmpty(bakAct))
          {
              return RedirectToAction("Index", "Home");
          }
          else
          {
              return RedirectToAction(bakAct, bakCtrl);
          }
      }
 
 
2.在html加入切換語系
<a href="@Url.Action("ChangeLang", "Home", new { langCode = "zh-TW" })">中文</a>
…
3.在Global.asax 設定cookie語言的資訊

protected void Application_BeginRequest(Object sender, EventArgs e)
      {
          HttpCookie myLang = Request.Cookies["lang"];
          if (myLang != null)
          {
              System.Threading.Thread.CurrentThread.CurrentCulture =
                  new System.Globalization.CultureInfo(myLang.Value);
              System.Threading.Thread.CurrentThread.CurrentUICulture =
                  new System.Globalization.CultureInfo(myLang.Value);
          }
      }
 

4.新增resource資源檔 增加欄位即可
參考 :  https://goo.gl/5gh9gw
編輯多國語系套件 : http://resxmanager.codeplex.com/

2017年3月14日 星期二

[Filter] OnActionExecuting


如果需要在進Action前執行特定行為,如過濾

就需要額外新增一個class並繼承ActionFilterAttribute

裡面有四個基本功能

Action,Result執行前後

範例 :
//public override void OnActionExecuting(ActionExecutingContext filterContext)       
//{       
//    string currentDomain = filterContext.HttpContext.Request.Headers["HOST"];       
//    List<string> domains = WebConfigurationManager.AppSettings["AllowDomain"].ToString().Split(',').ToList();       
//    if (!domains.Any(i => i.Contains(currentDomain)))       
//    {      
//        throw new Exception("未允許的網域");       
//    }       
//}

2016年4月18日 星期一

[Error] DI 使用autofac遇到的問題

 

2016-04-18_130649

解 : 要把dll加入參考

 

2016-04-18_102129

解 : webconfig 需設定autofac區段

 

2016-04-18_104937

2016年3月7日 星期一

[MVC] Global 建立排程


如果有定期需要發信或是備份等排程工作,可以開新專案用 WindowService來做,除此之外,這裡用一個偷懶的方式,就是直接在global的Application_Start加入timer 做排程,更進階的排程framework可以參考 ASP.NET 程式中的背景工作 (3) - 使用 Quartz.NET
 
以下展示簡易的方法 :
 
 

2015年12月24日 星期四

[MVC] 使用ActionFilterAttribute 紀錄Log

假設當Client發出一個搜尋的Request,我們希望可以在紀錄使用者搜尋的關鍵字,以便日後可以統計…

這個需求就可以利用ActionFilterAttribute來完成,首先先看下面進如Action的簡易流程示意圖 :


圖片出處

2015年12月18日 星期五

[C#][MVC] Facebook OAuth 驗證與登入

1. 申請自己的app : https://developers.facebook.com/apps/




 





2. 選擇要建立的app (範例網站)

3. 輸入app名稱

4. 選擇你的類型後, 點擊新增


























5. 看到此頁面就是成功了申請囉, 然後照著步驟走
5.1 記得設定你的網站網址 : ex. http://localhost:7115/




6. 回到 https://developers.facebook.com/apps/ 選擇TestWeb
7. 記住你的App ID
8. 在你的網站js輸入以下code (請自行重構)


// For FB
window.fbAsyncInit = function() {
    FB.init({
        appId: xxxxxx// App ID
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        xfbml: true,  // parse XFBML
        version: 'v2.5'
    });

    // Additional initialization code here
    FB.Event.subscribe('auth.authResponseChange', function (response) {
        if (response.status === 'connected') {
            // the user is logged in and has authenticated your
            // app, and response.authResponse supplies
            // the user's ID, a valid access token, a signed
            // request, and the time the access token
            // and signed request each expire
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
            var data = {
                token: accessToken
            }
            // TODO: Handle the access token
            console.log(uid);
            console.log(accessToken);
            ajaxServer('Home/FacebookLogin', data);
        } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook,
            // but has not authenticated your app
        } else {
            // the user isn't logged in to Facebook.
        }
    });
};

function fbLogout() {
    FB.logout(function (response) {
        window.location.reload();
        // user is now logged out
    });
}

// Load the SDK Asynchronously
(function(d){
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);

}(document));

function ajaxServer(url, data) {
    $.ajax({
        url: url,
        data: data,
        type: "POST",
        dataType: 'json',
        success: function (msg) {
            console.log(msg);
        },

        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

註.裡面的ajax 就是post到你的server, 

9. 至html頁面放入以下 :
<div class="fb-login-button" scope="public_profile,email" data-show-faces="true" data-width="400" data-max-rows="1"></div>
<a href="#" onclick="fbLogout();">FB Sign out</a>
<div id="fb-root"></div>
標籤scope就是你希望請求的資訊,可參考此 : https://developers.facebook.com/docs/facebook-login/permissions#reference


9.  server端(.net), 請到nuget 下載facebook套件  http://facebooksdk.net/docs/web/getting-started/

10. 寫一個Action :

        [HttpPost]
        public JsonResult FacebookLogin(string token)
        {
            var client = new FacebookClient(token);
            dynamic result = client.Get("me", new { fields = "name,id,email" });
            string name = result.name;
            string id = result.id;
            return Json(name, JsonRequestBehavior.AllowGet);
        }


2015年12月3日 星期四

[MVC][Error] js date物件無法 於mvc model binding

今天遇到一個很見鬼卻有很簡單的問題,
當使用js post時間欄位至server時,mvc 會有model binding幫我們做好繫結,變成強行別的DateTime,
但今天因為使用get方法,以及在query string串接js的date 物件,卻發現到server時欄位一直binding不起來,
最後發現如果是用query string 串接在轉換時會變成其他編碼,難怪mvc會看不懂 XD
範例如下 :

var a = new Date();

console.log(a);

//Thu Dec 03 2015 19:19:16 GMT+0800 (台北標準時間)
//實際http get : ?Thu%20Dec%2003%202015%2019:18:29%20GMT+0800%20(台北標準時間)



因此要就要自己轉換一下時間或是先編碼escape(Date);

2014年8月9日 星期六

[MVC] View要如何回傳List至controller (Model Binding To List Of Objects)

Q : View要如何回傳List<model>至controller

  1.  public JsonResult UpdateOrder(List<CategoryModel> CateList)
  2.  {
  3.     ...
  4.  }

A : 
model binding 就是利用表單 的name與物件的同名欄位做Reflection,
而對於List則需要在View的model name上加[index] 來達成 

ex.@Html.TestBox("Categorymodel[" + @i + "].ID, "value")
ps.要注意的是, index必須從0開始,不然就會繫結失敗

Q : 但是我不是用for loop, index也不是從0開始怎麼辦?

A : 額外設定Index讓程式知道,就可以用你專屬的流水號,而程式也可以binding到

  1.  @Html.Hidden("Categorymodel.Index", "你的流水號xxxxxxxxx")

[Error] MVC 發佈到 IIS 後,找不到首頁

Q: MVC 發佈到 IIS7 後,連到首頁跳403,無法正常導向到首頁


























截至網路


A: 我找到的原因是,IIS無法正常處理 MVC 的 route 設定,因為版本沒有設置到asp.net4.0

所以解法就是把asp.net4.0註冊出來。

步驟 :
1. 用系統管理員身份打開命令提示字元
















2. 去C槽 Windows\Microsoft.NET\Framework\ 找出自己4.0版本














3.註冊

cd \
cd
Windows\Microsoft.NET\Framework\v4.xxx.xxx
aspnet_regiis
-i







之後就可在IIS上找到ASP.NET4.0,
再到網站的應用程式集區設定成4.0即可囉~~






2014年3月23日 星期日

[MVC] WILL保哥演講


錯過這一場,希望之後會有影片><"