ASP.NET Core Web API集成WebDAV:PROPFIND请求404及Swagger报错问题
解决方案
一、解决PROPFIND请求404问题
你的404问题核心是路由参数绑定错误:当前请求的/api/webdav/yourfile.txt中,yourfile.txt是路由路径的一部分,但你的方法用[FromQuery] string path获取参数,导致实际path值为null,最终拼接的路径不存在,返回404。
修改步骤:
- 调整控制器路由,支持捕获任意子路径:将
[Route("api/webdav")]改为[Route("api/webdav/{*path}")],{*path}是通配符路由,会把api/webdav之后的所有路径内容绑定到path参数。 - 移除参数的
[FromQuery]标记,让路由自动绑定路径参数。 - 增加路径安全校验,防止目录遍历攻击(比如用户传入
../访问WebDAVData外的文件)。
修改后的控制器代码:
using Microsoft.AspNetCore.Mvc; namespace Playground.Controllers { [Route("api/webdav/{*path}")] [ApiController] public class WebDAVController : ControllerBase { private readonly string _baseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "WebDAVData"); public WebDAVController() { if (!Directory.Exists(_baseDirectory)) { Directory.CreateDirectory(_baseDirectory); } } [AcceptVerbs("PROPFIND")] public IActionResult Propfind(string path) { // 拼接完整路径并转为绝对路径 var fullPath = Path.GetFullPath(Path.Combine(_baseDirectory, path ?? "")); // 校验路径是否在WebDAVData目录内,防止目录遍历 if (!fullPath.StartsWith(_baseDirectory, StringComparison.OrdinalIgnoreCase)) { return Forbid(); } if (!System.IO.File.Exists(fullPath) && !Directory.Exists(fullPath)) { return NotFound(); } var fileInfo = new FileInfo(fullPath); var properties = new Dictionary<string, string> { { "CreationDate", fileInfo.CreationTime.ToString() }, { "LastModified", fileInfo.LastWriteTime.ToString() }, { "Size", fileInfo.Length.ToString() } }; return Ok(properties); } } }
此时重新发送PROPFIND请求:
curl -X PROPFIND http://localhost:5242/api/webdav/yourfile.txt -i
如果yourfile.txt存在于WebDAVData目录下,将返回200和属性信息。
二、解决Swagger不支持PROPFIND方法的问题
Swagger默认只支持标准HTTP方法(GET/POST/PUT/DELETE等),PROPFIND属于扩展方法,需要手动配置SwaggerGen来支持。
方案1:让Swagger忽略该API(简单快速)
如果不需要在Swagger文档中展示PROPFIND接口,直接在方法上添加[ApiExplorerSettings(IgnoreApi = true)]:
[AcceptVerbs("PROPFIND")] [ApiExplorerSettings(IgnoreApi = true)] public IActionResult Propfind(string path) { // ... 现有代码 }
方案2:配置Swagger支持PROPFIND方法
如果需要在Swagger中展示该接口,在Program.cs的Swagger配置中添加以下代码:
builder.Services.AddSwaggerGen(c => { // 注册支持PROPFIND方法的操作过滤器 c.OperationFilter<WebDAVOperationFilter>(); }); // 自定义操作过滤器,添加PROPFIND方法支持 public class WebDAVOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { var acceptVerbsAttribute = context.MethodInfo.GetCustomAttributes(typeof(AcceptVerbsAttribute), false) .Cast<AcceptVerbsAttribute>() .FirstOrDefault(); if (acceptVerbsAttribute?.Verbs.Contains("PROPFIND") == true) { operation.Method = OperationMethod.PROPFIND; } } }
注意:需要引用Microsoft.OpenApi.Models命名空间。
配置完成后,Swagger将不再抛出异常,并且会正确展示PROPFIND接口。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

