[英]Persisting data in Asp.Net MVC application
我的應用程序使我們的銷售團隊可以管理不同客戶的配置(例如:電子郵件模板,網站資源,css ..)。 在應用程序的每個頁面上都需要客戶端ID,以指示正在修改哪個客戶端。 布局中有一個下拉列表,因此您可以在客戶端之間切換。
到目前為止,我在每個頁面上傳遞了id,並將其作為查詢字符串傳遞給了我的鏈接
@Url.Action("Action", "Controller", new { clientId = Model.ClientId })
並且在包含客戶ID的每種形式中都有一個隱藏字段。
我不想使用會話,但是隨着應用程序的發展,在每個鏈接中傳遞客戶端ID並在每種形式中都有一個隱藏字段變得越來越麻煩。
你怎么看?
在ASP.NET MVC中 ,有三種方法ViewData, ViewBag and TempData
用於將數據從控制器傳遞到視圖並在下一個請求中傳遞。 與WebForm
一樣,您也可以使用Session
在用戶會話期間保留數據。 他們每個人都有自己的重要性。
如何使用
public ActionResult Index()
{
ViewBag.Name = "Monjurul Habib";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Monjurul Habib";
return View();
}
在視圖中:
@ViewBag.Name
@ViewData["Name"]
我建議使用Claims而不是傳遞客戶ID。 例如,一旦您的客戶端登錄,您就將客戶端的ID設置為Claim(實際上存儲在Cookie中)。 之后,您可以從控制器的“操作方法”中檢查“索賠”。 這是檢查Claim的示例:
public static bool HasClaim(string claimType, string claimValue)
{
ClaimsIdentity claimsIdentity = HttpContext.Current.User.Identity as ClaimsIdentity;
return claimsIdentity != null && claimsIdentity.HasClaim(claimType, claimValue);
}
我認為這種方式將是更容易,可維護和更清潔的解決方案。 我已經回答了有關基於聲明的訪問控制的問題,您也可以在此處進行檢查:
ASP.NET MVC中基於角色的訪問控制(RBAC)與基於聲明的訪問控制(CBAC)
您可以創建一個ClaimsAuthorizeAttribute為
public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
private readonly string _claimType;
private readonly string _claimValue;
public ClaimsAuthorizeAttribute(string claimType, string claimValue)
{
this._claimType = claimType;
this._claimValue = claimValue;
}
private static bool IsLoggedIn
{
get {
return HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated;
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
if (!IsLoggedIn)
return false;
return HasClaim(_claimType, _claimValue);
}
}
在您的Action方法中,按如下方式使用它:
[ClaimsAuthorize(ClaimTypes.Role, "Your Client Id")]
public ActionResult Index()
{
return View();
}
將數據存儲在會話中或設置自定義cookie。
自定義Cookie解決方案優於基於會話的解決方案的一個論據是,當ASP.NET必須查找會話並反序列化/序列化數據時,會涉及一些開銷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.