Shy*_*ikh 9 c# azure asp.net-web-api azure-functions
Azure功能应用程序引用用于构建视图的webApi
项目.razorEngine
cshtml
问题是访问cshtml文件.直到现在我正在使用:
HostingEnvironment.MapPath("~/Views/templates/") + "test.cshtml";
访问曾经使用webApi作为独立项目的文件.现在作为引用的程序集,路径的计算结果为
E:\Web\Proj.Func\bin\Debug\net461\test.cshtml
它不会评估为cshtml
文件的正确路径.
怎么解决这个?
当您添加一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是函数:
[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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
323 次 |
最近记录: |