How do you include .html or .asp file using razor?

2019-01-22 06:39发布

Is it possible to use server side include in Razor view engine to include .html or .asp file? We have an .html file and .asp files that contain website menus that are used for all of our websitse. Currently we use server side include for all of our sites so that we only need to change the mensu in one place.

I have the following code in the body of my _Layout.cshtml

<body>
<!--#include virtual="/serverside/menus/MainMenu.asp" -->   
<!--#include virtual="/serverside/menus/library_menu.asp" -->
<!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->
@RenderBody()
</body>

Instead of including the content of the file, if I do a view source, I see the literal text.

" <!--#include virtual="/serverside/menus/MainMenu.asp" --> 
    <!--#include virtual="/serverside/menus/library_menu.asp" -->
    <!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->"

14条回答
▲ chillily
2楼-- · 2019-01-22 06:46

Razor does not support server-side includes. The easiest solution would be copying the menu markup into your _Layout.cshtml page.

If you only needed to include .html files you could probably write a custom function that read the file from disk and wrote the output.

However since you also want to include .asp files (that could contain arbitrary server-side code) the above approach won't work. You would have to have a way to execute the .asp file, capture the generated output, and write it out to the response in your cshtml file.

In this case I would go with the copy+paste approach

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-22 06:46

Html.Include(relativeVirtualPath) Extension Method

I wanted to include files like this for documentation purposes (putting the contents of a file in a <pre> tag).

To do this I added an HtmlHelperExtension with a method that takes a relative virtual path (doesn't have to be an absolute virtual path) and an optional boolean to indicate whether you wish to html encode the contents, which by default my method does since I'm using it primarily for showing code.

The real key to getting this code to work was using the VirtualPathUtility as well as the WebPageBase. Sample:

// Assume we are dealing with Razor as WebPageBase is the base page for razor.
// Making this assumption we can get the virtual path of the view currently
// executing (will return partial view virtual path or primary view virtual
// path just depending on what is executing).
var virtualDirectory = VirtualPathUtility.GetDirectory(
   ((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);

Full HtmlHelperExtension Code:

public static class HtmlHelperExtensions
{
    private static readonly IEnumerable<string> IncludeFileSupportedExtensions = new String[]
    {
        ".resource",
        ".cshtml",
        ".vbhtml",
    };

    public static IHtmlString IncludeFile(
       this HtmlHelper htmlHelper, 
       string virtualFilePath, 
       bool htmlEncode = true)
    {
        var virtualDirectory = VirtualPathUtility.GetDirectory(
            ((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
        var fullVirtualPath = VirtualPathUtility.Combine(
            virtualDirectory, virtualFilePath);
        var filePath = htmlHelper.ViewContext.HttpContext.Server.MapPath(
            fullVirtualPath);

        if (File.Exists(filePath))
        {
            return GetHtmlString(File.ReadAllText(filePath), htmlEncode);
        }
        foreach (var includeFileExtension in IncludeFileSupportedExtensions)
        {
            var filePathWithExtension = filePath + includeFileExtension;
            if (File.Exists(filePathWithExtension))
            {
                return GetHtmlString(File.ReadAllText(filePathWithExtension), htmlEncode);
            }
        }
        throw new ArgumentException(string.Format(
@"Could not find path for ""{0}"".
Virtual Directory: ""{1}""
Full Virtual Path: ""{2}""
File Path: ""{3}""",
                    virtualFilePath, virtualDirectory, fullVirtualPath, filePath));
    }

    private static IHtmlString GetHtmlString(string str, bool htmlEncode)
    {
        return htmlEncode
            ? new HtmlString(HttpUtility.HtmlEncode(str))
            : new HtmlString(str);
    }
}
查看更多
混吃等死
4楼-- · 2019-01-22 06:47
@Html.Raw(File.ReadAllText(Server.MapPath("~/content/somefile.css")))
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-22 06:49

Create a HtmlHelper extension method that gets the contents of the files:

public static class HtmlHelpers
{
  public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string url)
  {
    return MvcHtmlString.Create(new WebClient().DownloadString(url));
  }
}

Usage:

@Html.WebPage("/serverside/menus/MainMenu.asp");
查看更多
三岁会撩人
6楼-- · 2019-01-22 06:51

Try implementing this HTML helper:

public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
    var filePath = HttpContext.Current.Server.MapPath(serverPath);

    // load from file
    using (var streamReader = File.OpenText(filePath))
    {
        var markup = streamReader.ReadToEnd();
        return new HtmlString(markup);
    }
}

or:

public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
    var filePath = HttpContext.Current.Server.MapPath(serverPath);

    var markup = File.ReadAllText(filePath);
    return new HtmlString(markup);
}
查看更多
Juvenile、少年°
7楼-- · 2019-01-22 06:51

I had the same issue when I tried to include an .inc file in MVC 4.

To solved this issue, I changed the suffix of the file to .cshtml and I added the following line

@RenderPage("../../Includes/global-banner_v4.cshtml")
查看更多
登录 后发表回答