如何使用自定义 AuthorizeAttribute 中的模型 return PartialView
How to return PartialView with model from custom AuthorizeAttribute
我正在做的事情的核心是,如果您转到 www.mysite。com/admin/index 我想渲染一个显示 "Unauthorized" 的局部视图有一个模型附加到它。我真的不希望该网站显示 www.mysite.com/error/unauthorized/ 因为当有人打电话告诉我我在“/error/unauthorized”页面上遇到错误时这不是很有用,当我真的希望他们说 "I got an unauthorized error on /admin/index page".
我的 CustomAuthorizeAttribute 继承自 AuthorizeAttribute,工作正常,但重定向除外。
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// returns boolean if it is good or not
}
然后我有我的 HandleUnauthorizedRequest,这是我需要用模型传递部分的地方:
if (context.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(context);
}
else
{
var viewResult = new PartialViewResult();
viewResult.ViewName = "~/Views/Shared/Unauthorized.cshtml";
viewResult.Model = new ViewModels.Unauthorized() { MyData = "My Data" }; // obviously can't do this as it is read-only
context.Result = viewResult;
}
我知道我可以删除 viewResult.Model 并只使用 ViewBag,但我 真的 希望有一些方法可以将模型传递给 Partial
由于 PartialViewResult.Model
是 get only 而 returns ViewData.Model
,您所要做的就是创建并设置 ViewData
属性:
var model = new ViewModels.Unauthorized() { MyData = "My Data" };
var viewResult = new PartialViewResult
{
ViewName = "~/Views/Shared/Unauthorized.cshtml",
ViewData = new ViewDataDictionary(model)
};
context.Result = viewResult;
我正在做的事情的核心是,如果您转到 www.mysite。com/admin/index 我想渲染一个显示 "Unauthorized" 的局部视图有一个模型附加到它。我真的不希望该网站显示 www.mysite.com/error/unauthorized/ 因为当有人打电话告诉我我在“/error/unauthorized”页面上遇到错误时这不是很有用,当我真的希望他们说 "I got an unauthorized error on /admin/index page".
我的 CustomAuthorizeAttribute 继承自 AuthorizeAttribute,工作正常,但重定向除外。
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// returns boolean if it is good or not
}
然后我有我的 HandleUnauthorizedRequest,这是我需要用模型传递部分的地方:
if (context.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(context);
}
else
{
var viewResult = new PartialViewResult();
viewResult.ViewName = "~/Views/Shared/Unauthorized.cshtml";
viewResult.Model = new ViewModels.Unauthorized() { MyData = "My Data" }; // obviously can't do this as it is read-only
context.Result = viewResult;
}
我知道我可以删除 viewResult.Model 并只使用 ViewBag,但我 真的 希望有一些方法可以将模型传递给 Partial
由于 PartialViewResult.Model
是 get only 而 returns ViewData.Model
,您所要做的就是创建并设置 ViewData
属性:
var model = new ViewModels.Unauthorized() { MyData = "My Data" };
var viewResult = new PartialViewResult
{
ViewName = "~/Views/Shared/Unauthorized.cshtml",
ViewData = new ViewDataDictionary(model)
};
context.Result = viewResult;