Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing cshtml in referenced webapi project

Azure function app references a webApi project which uses razorEngine to build cshtml view.

The problem is accessing the cshtml file. Till now I was using:

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

to access the file which used to work with webApi as a standalone project. Now as a referenced assembly the path evaluates to

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

which doesn't evaluate to be the right path to the cshtml file.

How to solve this?

like image 811
Shyamal Parikh Avatar asked Jan 22 '18 16:01

Shyamal Parikh


2 Answers

When you add a Web API project as a reference to another project, and use it like a Class Library, then HostingEnvironment.MapPath will not work. In fact the api controller in no more hosted and HostingEnvironment.IsHosted is false.

As an option you can write the code to find the file like following code, then the code will work in both cases, when it's hosted as Web API or when it's been used as a Class Library.

Just don't forget to include the files to output directory, so they will be copied near the bin folder of the Azure Function project.

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);
    }
}

And here is the function:

[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);
}
like image 131
Reza Aghaei Avatar answered Nov 05 '22 06:11

Reza Aghaei


You can use this code

AppContext.BaseDirectory + "Views\\templates\\" + "test.cshtml"
like image 33
Kahbazi Avatar answered Nov 05 '22 06:11

Kahbazi