I have changed the architecture of my ASP.Net application, I have a lot of links that refer to .json
files that are now served from .ashx
files. To maintain backward compatibility and to avoid changing the existing links I have tried to use an ASP.Net handler to rename the incoming http requests.
I have tried many solutions that I found on Stackoverflow but I cannot get it to work:
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);
}
have a look at URL Rewriting Middleware in ASP.NET Core and ASP.NET Core URL Rewriting
You can use the URL Rewriting middleware to rewrite the urls similar to this 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;
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.