首页 > 解决方案 > 如何使用 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);

}

标签: c#asp.net-core

解决方案


看看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;
            }
        }
    }
}

推荐阅读