Asp.Net Core Web相对路径、绝对路径整理

一、相对路径

1.关于Asp.Net Core中的相对路径主要包括两个部分:一、Web根目录,即当前网站的目录为基础;二、内容目录wwwroot文件夹,对于静态文件都放在这个目录。

2.获取控制器,Action的路径

对于控制器、视图的链接生成,主要通过视图上下文、控制器上下文的Url对象

Url对象实现了IUrlHelper接口,主要功能是获取网站的相对目录,也可以将‘~’发号开头的转换成相对目录。

    //
    // 摘要:
    //     Defines the contract for the helper to build URLs for ASP.NET MVC within an application.
    public interface IUrlHelper
    {
        //
        // 摘要:
        //     Gets the Microsoft.AspNetCore.Mvc.IUrlHelper.ActionContext for the current request.
        ActionContext ActionContext { get; }

        //
        // 摘要:
        //     Generates a URL with an absolute path for an action method, which contains the
        //     action name, controller name, route values, protocol to use, host name, and fragment
        //     specified by Microsoft.AspNetCore.Mvc.Routing.UrlActionContext. Generates an
        //     absolute URL if Microsoft.AspNetCore.Mvc.Routing.UrlActionContext.Protocol and
        //     Microsoft.AspNetCore.Mvc.Routing.UrlActionContext.Host are non-null.
        //
        // 参数:
        //   actionContext:
        //     The context object for the generated URLs for an action method.
        //
        // 返回结果:
        //     The generated URL.
        string Action(UrlActionContext actionContext);
        //
        // 摘要:
        //     Converts a virtual (relative) path to an application absolute path.
        //
        // 参数:
        //   contentPath:
        //     The virtual path of the content.
        //
        // 返回结果:
        //     The application absolute path.
        //
        // 备注:
        //     If the specified content path does not start with the tilde (~) character, this
        //     method returns contentPath unchanged.
        string Content(string contentPath);
        //
        // 摘要:
        //     Returns a value that indicates whether the URL is local. A URL is considered
        //     local if it does not have a host / authority part and it has an absolute path.
        //     URLs using virtual paths ('~/') are also local.
        //
        // 参数:
        //   url:
        //     The URL.
        //
        // 返回结果:
        //     true if the URL is local; otherwise, false.
        bool IsLocalUrl(string url);
        //
        // 摘要:
        //     Generates an absolute URL for the specified routeName and route values, which
        //     contains the protocol (such as "http" or "https") and host name from the current
        //     request.
        //
        // 参数:
        //   routeName:
        //     The name of the route that is used to generate URL.
        //
        //   values:
        //     An object that contains route values.
        //
        // 返回结果:
        //     The generated absolute URL.
        string Link(string routeName, object values);
        //
        // 摘要:
        //     Generates a URL with an absolute path, which contains the route name, route values,
        //     protocol to use, host name, and fragment specified by Microsoft.AspNetCore.Mvc.Routing.UrlRouteContext.
        //     Generates an absolute URL if Microsoft.AspNetCore.Mvc.Routing.UrlActionContext.Protocol
        //     and Microsoft.AspNetCore.Mvc.Routing.UrlActionContext.Host are non-null.
        //
        // 参数:
        //   routeContext:
        //     The context object for the generated URLs for a route.
        //
        // 返回结果:
        //     The generated URL.
        string RouteUrl(UrlRouteContext routeContext);
    }
View Code

使用示例:

<p>
  ~转相对目录:  @Url.Content("~/test/one")
</p>

输出:/test/one

3.获取当前请求的相对路径

1.在Asp.Net Core中请求路径信息对象为PathString 对象

注:改对象没有目前没有绝对路径相关信息。

<p>
    @{
        PathString _path = this.Context.Request.Path;
        //获取当前请求的相对地址
        this.Write(_path.Value);
    }
</p>

输出:/path

2.获取当前视图的相对路径

注:视图上下文中的Path对象就是当前视图的相对位置,string类型

<p>
 当前视图的相对目录:   @Path
</p>

输出:/Views/Path/Index.cshtml

二、获取绝对路径

HostingEnvironment是承载应用当前执行环境的描述,它是对所有实现了IHostingEnvironment接口的所有类型以及对应对象的统称。

如下面的代码片段所示,一个HostingEnvironment对象承载的执行环境的描述信息体现在定义这个接口的6个属性上。ApplicationNameEnvironmentName分别代表当前应用的名称和执行环境的名称。WebRootPathContentRootPath是指向两个根目录的路径,前者指向的目录用于存放可供外界通过HTTP请求访问的资源,后者指向的目录存放的则是应用自身内部所需的资源。至于这个接口的ContentRootFileProviderWebRootFileProvider属性返回的则是针对这两个目录的FileProvider对象。如下所示的HostingEnvironment类型是对IHostingEnvironment接口的默认实现。

更多参考:http://www.cnblogs.com/artech/p/hosting-environment.html

    //
    // 摘要:
    //     Provides information about the web hosting environment an application is running
    //     in.
    public interface IHostingEnvironment
    {
        //
        // 摘要:
        //     Gets or sets the name of the environment. This property is automatically set
        //     by the host to the value of the "ASPNETCORE_ENVIRONMENT" environment variable.
        string EnvironmentName { get; set; }
        //
        // 摘要:
        //     Gets or sets the name of the application. This property is automatically set
        //     by the host to the assembly containing the application entry point.
        string ApplicationName { get; set; }
        //
        // 摘要: wwwroot目录的绝对目录
        string WebRootPath { get; set; }
        //
        // 摘要:
        //     Gets or sets an Microsoft.Extensions.FileProviders.IFileProvider pointing at
        //     Microsoft.AspNetCore.Hosting.IHostingEnvironment.WebRootPath.
        IFileProvider WebRootFileProvider { get; set; }
        //
        // 摘要:当前网站根目录绝对路径
        string ContentRootPath { get; set; }
        //
        // 摘要:
        //     Gets or sets an Microsoft.Extensions.FileProviders.IFileProvider pointing at
        //     Microsoft.AspNetCore.Hosting.IHostingEnvironment.ContentRootPath.
        IFileProvider ContentRootFileProvider { get; set; }
    }

获取当前网站根目录绝对路径,设置任何地方可以使用:

1.定义全局静态变量:

    public class TestOne
    {
        public static IHostingEnvironment HostEnv;
    }

2.在启动文件Startup中赋值:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
{
    TestOne.ServiceProvider = svp;

    TestOne.HostEnv = env;
}

3.输出根目录信息:

<p>
    @{ 
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(TestOne.HostEnv);
        this.Write(json);
        <script>
            console.info(@Html.Raw(json));
        </script>
    }
</p>

结果:

 

三、相对路径转绝对路径

注:目前没有找到直接转换的方法,但是网站根目录绝对路径+相对路径,就是视图或静态文件的绝对路径。可以自己封装一下。

<p>
    @{
        //获取当前视图的绝对路径
        string viewPath = TestOne.HostEnv.ContentRootPath + Path;
        this.Write(viewPath);
    }
</p>

输出:F:\SolutionSet\CoreSolution\Core_2.1\Core_Ng_2.1/Views/Path/Index.cshtml,可以直接访问到文件。

更多:

.Net Core Bitmap位图处理

Asp.Net Core 文件上传处理

Asp.Net Core获取当前上线文对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: dropzone.js 是一个非常流行的文件上传库,可以方便地在网页中实现文件拖拽上传的功能。而 ASP.NET Core WebAPI 是一个用于构建 Web API 的框架,可以快速地开发和部署具有高性能和可伸缩性的 Web API。 要在 ASP.NET Core WebAPI 中集成 dropzone.js,首先需要在前端代码中引入 dropzone.js 相关的脚本和样式文件。然后,在页面中创建一个用于接收文件上传的表单,并将其配置为使用 dropzone.js 进行文件上传。可以通过配置一些参数来自定义上传行为,例如设置文件上传的最大数量、文件大小限制、文件类型限制等。 在后端代码中,需要创建一个用于处理文件上传的 API 接口,该接口会接收前端发起的文件上传请求,并将上传的文件保存到指定的位置。可以使用 ASP.NET Core WebAPI 提供的 HttpRequest 对象来处理文件上传,通过读取请求的文件流来获取上传的文件内容,并将文件保存到指定的文件夹中。 在接收到文件上传请求后,需要进行一些验证和处理操作。例如,可以检查文件大小和类型是否符合要求,并根据需求进行相应的文件处理,例如修改文件名称、生成缩略图、写入数据库等。处理完成后,可以通过 API 接口返回相应的结果,例如返回上传成功的消息或返回上传失败的原因。 总结来说,使用 dropzone.js 和 ASP.NET Core WebAPI 可以很方便地实现文件上传功能。前端使用 dropzone.js 实现文件拖拽上传,后端使用 ASP.NET Core WebAPI 接受并处理上传的文件。通过结合使用这两个工具,可以轻松地实现一个功能强大且易于维护的文件上传功能。 ### 回答2: dropzone.js是一个基于JavaScript的文件上传库,它可以与asp.net core webapi配合使用来进行文件上传的处理。在使用dropzone.js时,我们需要引入相关的JavaScript和CSS文件,并建立一个HTML表单元素作为文件上传的区域。 在asp.net core webapi中,我们可以编写一个控制器来处理文件上传的请求。首先,我们需要在控制器中添加一个HttpPost方法,用于接收从前端传递过来的文件数据。然后,我们可以使用IFormFile接口来接收和处理上传的文件。 具体的实现步骤如下: 1. 在前端的HTML中,我们需要引入dropzone.js的相关文件,并在表单中定义一个用于文件上传的区域。可以设置一些参数来自定义文件上传的行为。 2. 在asp.net core webapi的控制器中,添加一个HttpPost方法,并使用[FromForm]特性将上传的文件绑定到IFormFile类型的参数中。 3. 在HttpPost方法中,可以对上传的文件进行处理,比如保存到服务器指定的路径中、返回文件的信息等。 主要的代码示例如下: 前端HTML代码: ```html <form action="/api/upload" class="dropzone" id="my-dropzone"></form> ``` 前端JavaScript代码: ```javascript Dropzone.options.myDropzone = { url: "/api/upload", maxFiles: 10, maxFilesize: 5, acceptedFiles: ".pdf,.jpg,.png", init: function () { this.on("success", function (file, response) { console.log("File uploaded:", file); }); }, }; ``` 后端C#代码: ```csharp [ApiController] [Route("api/[controller]")] public class UploadController : ControllerBase { [HttpPost] public async Task<IActionResult> UploadFile([FromForm] IFormFile file) { // 对上传的文件进行处理,比如保存到指定路径中 if (file != null && file.Length > 0) { var filePath = Path.Combine("path/to/save", file.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } } return Ok(new { message = "File uploaded successfully." }); } } ``` 通过以上代码,我们可以在前端页面中使用dropzone.js来实现文件的上传,并在后端的asp.net core webapi中编写相应的控制器来处理上传的文件。这样就可以实现一个基于dropzone.js和asp.net core webapi的文件上传功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值