简体   繁体   中英

How to return PartialView with model from custom AuthorizeAttribute

At the core of what I'm doing, what I would like is if you go to www.mysite.com/admin/index I want to render a partial view that shows "Unauthorized" that has a Model attached to it. I was really not wanting the site to show www.mysite.com/error/unauthorized/ as that is not very useful when someone calls up and tells me I got an error on "/error/unauthorized" page, when I really want them to say "I got an unauthorized error on /admin/index page".

I have my CustomAuthorizeAttribute that inherits from AuthorizeAttribute working just fine, other than the redirect.

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    // returns boolean if it is good or not
}

Then I have my HandleUnauthorizedRequest and this is where I need to pass in a partial with a model:

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;
}

I know I can remove viewResult.Model and just use the ViewBag, but I was really hoping there was some way to pass in a model to the Partial

Since PartialViewResult.Model is get only and returns ViewData.Model , all you have to do is to create and set the ViewData property:

var model = new ViewModels.Unauthorized() { MyData = "My Data" };
var viewResult = new PartialViewResult
{
    ViewName = "~/Views/Shared/Unauthorized.cshtml",
    ViewData = new ViewDataDictionary(model)
};
context.Result = viewResult;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM