Add namespace to all views in ASP.NET MVC 6

时间秒杀一切 提交于 2019-12-09 14:07:10

问题


I’m using MVC 6 and would like to be able to access a particular namespace globally from all of my Razor views. In MVC 5 this was fairly simple; I’d just add the following code to my ~/views/web.config file:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Optimization"/>
            <add namespace="System.Web.Routing" />
            <add namespace="MyProject.WebUI" />
            <add namespace="MyProject.WebUI.Helpers" /><!-- Added this line -->
        </namespaces>
    </pages>
</system.web.webPages.razor>

Where I’ve added access to the MyProject.WebUI.Helpers namespace.

In ASP.NET 5, and therefore MVC 6, the web.config file has be done away with, so I’m not sure how to go about doing this any more. I’ve tried searching for an answer, but all I can find is how to do it in current versions of ASP.NET rather than v5.

Any ideas?

Edit: Clarified which web.config file I would have used.


回答1:


For <= beta3 bits (what you're most likely using) you should add an @using statements to your _ViewStart.cshtml. Aka:

_ViewStart.cshtml: @using MyProject.WebUI.Helpers

If you don't have a _ViewStart.cshtml you can create one and just make sure it's in the same path or parent path of the view you want it to affect.

For beta4 bits, this functionality was moved to a new file called _GlobalImport.cshtml; _ViewStart.cshtml was transitioned back to its original functionality (just running code, not inheriting directives). Therefore:

_GlobalImport.cshtml: @using MyProject.WebUI.Helpers

For beta5 bits, _GlobalImport.cshtml was renamed to _ViewImports.cshtml




回答2:


Add your namespaces to the_ViewImports.cshtml file (it's under the Views folder).

Example file:

@using Microsoft.AspNetCore.Identity
@using Jifiti.Registry.Web.Models.AccountViewModels
@using Jifiti.Registry.Web.Models.ManageViewModels

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers



回答3:


I'm on beta 7 and I had to use

@using System.Security.Principal
@using System.Security.Claims

@Context.User.GetUserId()


来源:https://stackoverflow.com/questions/28719298/add-namespace-to-all-views-in-asp-net-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!