MVC 6 @inherit RazorPage

I am trying to port an MVC 5 application to ASP.NET 5 MVC 6 (beta 7). There were problems using the directives @inheritsand @model. Works great when used separately.

In mine, _ViewImportsI added a directive @inheritsto use the base page with some user custom properties.

public abstract class BaseViewPage<TModel> : RazorPage<TModel>
{
    protected MyPrincipal AppUser
    {
        get
        {
            return new MyPrincipal(this.User as ClaimsPrincipal);
        }
    }
}

_ViewImports.cshttml

@inherits CommonWeb.BaseViewPage<TModel>
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

And then I can go to AppUser. into all my ideas. This works if I dont use a strongly typed representation. If I add the directive @modelin any view, the inherited view page will disappear.

Help rate

Update:

I did this successfully using the custom pageBaseType in web.config in previous versions.

.

public class ViewHelper
{
    ViewContext _context;

    public ViewHelper(ViewContext context)
    {
        _context = context;
    }

    public MyPrincipal AppUser
    {
        get
        {
            return new MyPrincipal(_context.HttpContext.User as ClaimsPrincipal);
        }
    }

    public string ControllerName
    {
        get
        {
            return _context.RouteData.Values["controller"].ToString();
        }
    }
}

:

@{ var viewHelper = new ViewHelper(ViewContext);}

?

+4
1

MVC 6 , @inject. ( @inject IFoo Foo Foo IFoo)

IAppUserAccessor , :

public interface IAppUserAccessor
{
    MyPrincipal GetAppUser();
}

AppUserAccessor, :

public class AppUserAccessor : IAppUserAccessor
{
    private IHttpContextAccessor httpContextProvider;
    public AppUserAccessor(IHttpContextAccessor httpContextProvider)
    {
        this.httpContextProvider = httpContextProvider;
    }

    public MyPrincipal GetAppUser()
    {
        return new MyPrincipal (
                       httpContextProvider.HttpContext.User as ClaimsPrincipal);            
    }
}

, ConfigureServices Startup.cs:

services.AddTransient<IAppUserAccessor, AppUserAccessor>();

, @inject, IAppUserAccessor . ViewImports.cshtml, .

@inject WebApplication4.Services.IAppUserAccessor AppUserAccessor

:

@AppUserAccessor.GetAppUser()

, , IActionContextAccessor :

public AppUserAccessor(IHttpContextAccessor httpContextProvider, IActionContextAccessor actionContextAccessor)
{
    this.httpContextProvider = httpContextProvider;
    this.actionContextAccessor = actionContextAccessor;
}

...

public string ControllerName
{
    get { return actionContextAccessor.ActionContext.RouteData.Values["controller"].ToString(); }            
}

, AppUserAccessor , . , :)

, . , . (, /URL-, IUrlHelper)

ViewContext

, 8 ViewContext, RC. .

+4

Source: https://habr.com/ru/post/1609060/


All Articles