【问题标题】:Accessing cshtml in referenced webapi project在引用的 webapi 项目中访问 c​​shtml
【发布时间】:2018-07-01 08:04:54
【问题描述】:

Azure 函数应用引用了一个 webApi 项目,该项目使用 razorEngine 构建 cshtml 视图。

问题在于访问 cshtml 文件。直到现在我还在使用:

HostingEnvironment.MapPath("~/Views/templates/") + "test.cshtml";

访问曾经作为独立项目使用 webApi 的文件。现在作为一个引用的程序集,路径评估为

E:\Web\Proj.Func\bin\Debug\net461\test.cshtml

评估结果不是cshtml 文件的正确路径。

如何解决?

【问题讨论】:

  • 文件“test.cshtml”是否被复制到Debug文件夹中?
  • 调试文件夹不包含test.cshtml
  • 尝试在 Visual Studio 的 test.cshtml 文件的属性中将 copyAlways 属性设置为 true,看看是否有帮助?
  • 没有,试过了。实际上引用的程序集只是一个 DLL。
  • 也许你应该尝试嵌入你的cshtml。

标签: c# azure asp.net-web-api azure-functions


【解决方案1】:

当您添加一个 Web API 项目作为对另一个项目的引用并将其用作类库时,HostingEnvironment.MapPath 将不起作用。事实上,不再托管的 api 控制器和HostingEnvironment.IsHosted 是错误的。

作为一个选项,您可以编写代码来查找文件,如下面的代码,然后代码在两种情况下都可以工作,无论是作为 Web API 托管还是作为类库使用。

只是不要忘记将文件包含到输出目录中,因此它们将被复制到 Azure Function 项目的 bin 文件夹附近。

using System.IO;
using System.Reflection;
using System.Web.Hosting;
using System.Web.Http;
public class MyApiController : ApiController
{
    public string Get()
    {
        var relative = "Views/templates/test.cshtml";
        var abosolute = "";
        if (HostingEnvironment.IsHosted)
            abosolute = HostingEnvironment.MapPath(string.Format("~/{0}", relative));
        else
        {
            var root = new DirectoryInfo(Path.GetDirectoryName(
                Assembly.GetExecutingAssembly().Location)).Parent.FullName;
            abosolute = Path.Combine(root, relative.Replace("/", @"\"));
        }
        return System.IO.File.ReadAllText(abosolute);
    }
}

这里是函数:

[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
    HttpRequestMessage req, TraceWriter log)
{
    log.Info("Running");
    var api = new MyApiController();
    var result = await Task.Run(() => api.Get());
    return req.CreateResponse(HttpStatusCode.OK, result);
}

【讨论】:

  • 这正是我解决它的方法。而不是直接在ApiController 中包含路径代码。我使用了一个单独的服务,它的方法被WebApiAzure Func 引用。将等待 1-2 天,然后再选择此作为答案。
  • 太棒了!是的,这只是一个示例,为了简单起见,我只是将整个代码放在控制器中。
  • Task.Run()使用的目的是什么?
  • @LeonidVasilyev 满足编译器并防止它抱怨。这不是必需的。
  • 您可以删除async 修饰符并将Task&lt;HttpResponseMessage&gt; 返回类型替换为HttpResponseMessageGet()函数无论如何都使用同步文件IO。
【解决方案2】:

你可以使用这个代码

AppContext.BaseDirectory + "Views\\templates\\" + "test.cshtml"

【讨论】:

  • 输出是什么?
  • C:\Users\Shyamal\AppData\Local\Azure.Functions.Cli\1.0.7\Views\templates\test.cshtml 找不到路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多