You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含.aspx的URL重定向至ASP.NET Core Web API?

实现方案

1. 编写URL重写中间件拦截旧请求

直接写个中间件就能拦截/default.aspx的请求,把它转发到新的控制器接口,同时自动保留原查询参数。有两种实现方式:

快速实现:在Program.cs中编写内联中间件

把这段代码放在app.UseRouting()之前:

app.Use(async (context, next) =>
{
    // 匹配旧的default.aspx路径,忽略大小写
    if (context.Request.Path.Equals("/default.aspx", StringComparison.OrdinalIgnoreCase))
    {
        // 将请求路径替换为新控制器的路由,比如/api/search
        context.Request.Path = "/api/search";
    }
    await next();
});

规范实现:封装为独立中间件类

如果后续需要扩展逻辑,单独封装类更易维护:

public class LegacyUrlMiddleware
{
    private readonly RequestDelegate _next;

    public LegacyUrlMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (context.Request.Path.Equals("/default.aspx", StringComparison.OrdinalIgnoreCase))
        {
            context.Request.Path = "/api/search";
        }
        await _next(context);
    }
}

// 写个扩展方法方便注册
public static class LegacyUrlMiddlewareExtensions
{
    public static IApplicationBuilder UseLegacyUrlRedirect(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<LegacyUrlMiddleware>();
    }
}

然后在Program.cs中注册中间件:

app.UseLegacyUrlRedirect();
// 注意必须放在UseRouting之前
app.UseRouting();

2. 配置控制器处理请求并返回XML

先编写对应的控制器,接收原有的查询参数:

[ApiController]
[Route("api/[controller]")]
public class SearchController : ControllerBase
{
    [HttpGet]
    // 强制返回XML格式
    [Produces("application/xml")]
    public IActionResult Get([FromQuery] string q, [FromQuery] string category)
    {
        // 替换为你的实际业务逻辑,生成要返回的数据对象
        var result = new SearchResult
        {
            Query = q,
            Category = category,
            Items = new List<SearchItem>
            {
                new SearchItem { Id = 1, Name = "测试结果1" },
                new SearchItem { Id = 2, Name = "测试结果2" }
            }
        };

        return Ok(result);
    }
}

// 示例实体类,根据实际业务调整
public class SearchResult
{
    public string Query { get; set; }
    public string Category { get; set; }
    public List<SearchItem> Items { get; set; }
}

public class SearchItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}

接下来要让Web API支持XML序列化,在Program.cs中添加XML格式化器:

builder.Services.AddControllers()
    .AddXmlSerializerFormatters() // 基础XML序列化支持
    .AddXmlDataContractSerializerFormatters(); // 可选,支持DataContract序列化场景

如果需要强制返回XML(忽略请求头的Accept设置),除了添加[Produces("application/xml")]特性,也可以在中间件中修改请求头:

// 在中间件的路径替换逻辑后添加
context.Request.Headers.Accept = "application/xml";

3. 测试验证

发起请求http://localhost:xxxx/default.aspx?q=test&category=test_category,就能得到XML格式的响应,示例如下:

<SearchResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Query>test</Query>
  <Category>test_category</Category>
  <Items>
    <SearchItem>
      <Id>1</Id>
      <Name>测试结果1</Name>
    </SearchItem>
    <SearchItem>
      <Id>2</Id>
      <Name>测试结果2</Name>
    </SearchItem>
  </Items>
</SearchResult>

内容的提问来源于stack exchange,提问作者pka246

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 03:23:17