首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.net核心,如何使用额外的前导斜线处理路由

.net核心,如何使用额外的前导斜线处理路由
EN

Stack Overflow用户
提问于 2019-12-12 12:01:59
回答 3查看 3K关注 0票数 3

我需要处理一个传入的请求,它的形式是://ohif/study/1.1/系列--注意前面的exta斜杠

我的控制器签名是:

代码语言:javascript
复制
[Route("ohif/study/{studyUid}/series")]
[HttpGet]
public IActionResult GetStudy(string studyUid)

如果我将传入的请求修改为/ohif/study/1.1/系列,那么效果很好。

然而,当我使用//ohif/study/1.1/系列时,路线不会被击中。

此外,我还尝试了:路由(“/ohif/study/{studyUid}/series”)和路由(“//ohif/study/{studyUid}/series”)

都失败了。不幸的是,我无法更改来自外部应用程序的传入请求。这条路有什么窍门吗?我在.NET Core3.0中工作。

Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware更新注意:已激活日志记录,并且看到asp.net核心正在分析路由,我收到消息:没有为记录器的请求路径//ohif//1.1/系列找到候选

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-12 15:25:57

在web服务器级别重写URL,例如对于IIS,可以使用URL重写模块自动将//ohif/study/1.1/series重定向到/ohif/study/1.1/series。这不是你申请的工作。

票数 3
EN

Stack Overflow用户

发布于 2020-04-26 15:13:02

那么处理双斜杠的中间件呢?

代码语言:javascript
复制
app.Use((context, next) =>
            {
                if (context.Request.Path.Value.StartsWith("//"))
                {
                    context.Request.Path = new PathString(context.Request.Path.Value.Replace("//", "/"));
                }
                return next();
            });
票数 7
EN

Stack Overflow用户

发布于 2022-09-13 12:21:06

我接受了Ravi的回答,充实了一个中间件。中间件是很好的,因为它是封装的,易于测试,可以注入一个记录器,更易读,等等。

代码语言:javascript
复制
app.UseDoubleSlashHandler();

代码和测试:

代码语言:javascript
复制
public class DoubleSlashMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<DoubleSlashMiddleware> _logger;

    public DoubleSlashMiddleware(RequestDelegate next, ILogger<DoubleSlashMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        _logger.LogInformation($"Invoking {nameof(DoubleSlashMiddleware)} on {context.Request.Path}");

        context.Request.Path = context.Request.Path.FixDoubleSlashes();

        // Call the next delegate/middleware in the pipeline.
        await _next(context);
    }
}

public static class DoubleSlashMiddlewareExtensions
{
    public static IApplicationBuilder UseDoubleSlashHandler(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<DoubleSlashMiddleware>();
    }
}

[TestClass()]
public class DoubleSlashMiddlewareTests
{
    private DoubleSlashMiddleware _sut;
    private ILogger<DoubleSlashMiddleware> _logger;
    private bool _calledNextMiddlewareInPipeline;

    [TestInitialize()]
    public void TestInitialize()
    {
        _logger = Substitute.For<ILogger<DoubleSlashMiddleware>>();
        Task Next(HttpContext _)
        {
            _calledNextMiddlewareInPipeline = true;
            return Task.CompletedTask;
        }
        _sut = new DoubleSlashMiddleware(Next, _logger);
    }

    [TestMethod()]
    public async Task InvokeAsync()
    {
        // Arrange
        _calledNextMiddlewareInPipeline = false;

        // Act
        await _sut.InvokeAsync(new DefaultHttpContext());

        // Assert
        _logger.ReceivedWithAnyArgs(1).LogInformation(null);
        Assert.IsTrue(_calledNextMiddlewareInPipeline);
    }
}

字符串方法来执行替换:

代码语言:javascript
复制
public static class RoutingHelper
{
    public static PathString FixDoubleSlashes(this PathString path)
    {
        if (string.IsNullOrWhiteSpace(path.Value))
        {
            return path;
        }
        if (path.Value.Contains("//"))
        {
            return new PathString(path.Value.Replace("//", "/"));
        }
        return path;
    }
}

[TestClass()]
public class RoutingHelperTests
{
    [TestMethod()]
    [DataRow(null, null)]
    [DataRow("", "")]
    [DataRow("/connect/token", "/connect/token")]
    [DataRow("//connect/token", "/connect/token")]
    [DataRow("/connect//token", "/connect/token")]
    [DataRow("//connect//token", "/connect/token")]
    [DataRow("/connect///token", "/connect/token")]
    public void FixDoubleSlashes(string input, string expected)
    {
        // Arrange
        var path = new PathString(input);

        // Act
        var actual = path.FixDoubleSlashes();

        // Assert
        Assert.AreEqual(expected, actual.Value);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59304132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档