[英]How can I authenticate my MVC5 application through an existing WebAPI?
[英]How can I spread custom object through my MVC application?
假設我有一個與嘗試訪問我的網站的每個用戶相似的對象。 一種會話作用域對象,應該在我整個“應用程序”中的每個視圖/模型/控制器上可見。
我想在調用頁面時創建它,並通過來自我自己數據庫的數據填充它。
然后,在View(例如)上調用myObject.Title。 在WebForms上,我正在擴展UserControl的類,例如:
public class iUserControl : System.Web.UI.UserControl
{
protected MyCurrentPage myCurrentPage;
public iUserControl()
{
}
protected override void OnLoad(EventArgs e)
{
myCurrentPage = new MyCurrentPageWrapper();
}
}
比方說,對於每個UserControl,都是這樣的:
public partial class context_pippo_MyOwnUserControl : iUserControl
在MVC上,我看不到每個控件的任何擴展,那么如何實現這種過程? 我想擺脫在Session上存儲元素的麻煩。
如果我正確理解問題,那么我認為我在一個項目中做了類似的事情。 我有這樣的事情:
public interface IControllerBaseService
{
IUserService UserService {get;set;}
ShoppingMode ShoppingMode {get;set;}
...
}
public abstract class ControllerBase : Controller, IControllerBaseService
{
public IUserService UserService {get;set;} // this is injected by IoC
public ShoppingMode ShoppingMode
{
get
{
return UserService.CurrentShoppingMode; // this uses injected instance to get value
}
...
}
只要我用IoC容器創建控制器實例,UserService屬性就由容器注入。
您現在可以從如下視圖訪問您的界面:
(IControllerBaseService)ViewContext.Controller
要為IControllerBaseService
最常用的屬性提供快捷方式,我有幾種擴展方法,如下所示:
public static ShoppingMode CurrentShoppingMode(this HtmlHelper helper)
{
return ((IContollerBaseService)helper.ViewContext.Controller).ShoppingMode;
}
所以在看來它就像@Html.CurrentShoppingMode()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.