c# - 如何使用 ASP.NET 处理程序将带有 .json 的 url 重写为 .ashx
问题描述
我已经更改了 ASP.Net 应用程序的体系结构,我有很多链接指向.json
现在从文件提供的.ashx
文件。为了保持向后兼容性并避免更改现有链接,我尝试使用 ASP.Net 处理程序来重命名传入的 http 请求。
我已经尝试了许多在 Stackoverflow 上找到的解决方案,但我无法让它工作:
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
string newUrl = context.Request.RawUrl.Replace(".json", ".ashx");
context.Server.Transfer(newUrl);
}
解决方案
看看ASP.NET Core 中的URL 重写中间件和ASP.NET Core URL 重写
您可以使用 URL 重写中间件来重写类似这样的 url startup.cs
:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
namespace WebApplication1
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var options = new RewriteOptions()
.Add(RedirectJsonFileRequests);
app.UseRewriter(options);
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
/// <summary>
/// Redirect all requests to .json extension files to .ashx extensions, copy across the query string, if any
/// </summary>
/// <param name="context"></param>
public static void RedirectJsonFileRequests(RewriteContext context)
{
var request = context.HttpContext.Request;
// Because the client is redirecting back to the same app, stop
// processing if the request has already been redirected.
if (request.Path.Value.EndsWith(".ashx", StringComparison.OrdinalIgnoreCase))
{
return;
}
if (request.Path.Value.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status301MovedPermanently;
context.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] =
request.Path.Value.Replace(".json", ".ashx", StringComparison.OrdinalIgnoreCase) + request.QueryString;
}
}
}
}
推荐阅读
- javascript - Wrapper 不会占用全部空间
- java - Android缓存影响变量的值?
- swift - 如何完全禁用导航栏,但在 SwiftUI 中保留 NavigationView?
- macos - 在命令行上在 mac 上链接 GLEW 和 GLFW3
- c++ - QwebEnginePage Doesn't print html code Qt
- python - Django - 外键和管理页面
- python - 如何访问 Pandas 数据框的 Python 字典中的值、修改数据框并更新字典值
- python - 我如何在python中处理客户端错误处理
- python - 通过提供 stingpath 在函数中调用 pandas 数据框
- python - Python:KNN 回归拟合返回错误