IT TIP

ASP.NET 라우팅을 사용하여 정적 파일 제공

itqueen 2020. 10. 29. 20:19
반응형

ASP.NET 라우팅을 사용하여 정적 파일 제공


MVC가 아닌 ASP.Net 라우팅을 사용하여 정적 파일을 제공 할 수 있습니까?

내가 라우팅하고 싶다고 말해

http://domain.tld/static/picture.jpg

...에

http://domain.tld/a/b/c/picture.jpg

재 작성된 URL이 즉석에서 계산된다는 점에서 동적으로 수행하고 싶습니다. 한 번에 고정 경로를 설정할 수 없습니다.

어쨌든 다음과 같은 경로를 만들 수 있습니다.

routes.Add(
  "StaticRoute", new Route("static/{file}", new FileRouteHandler())
);

에서 FileRouteHandler.ProcessRequest방법 나는에서 경로를 다시 작성할 수 있습니다 /static/picture.jpg에를 /a/b/c/picture.jpg. 그런 다음 정적 파일에 대한 처리기를 만들고 싶습니다. ASP.NET StaticFileHandler은이를 위해를 사용합니다 . 불행히도이 클래스는 내부 클래스입니다. 리플렉션을 사용하여 처리기를 만들려고 시도했으며 실제로 작동합니다.

Assembly assembly = Assembly.GetAssembly(typeof(IHttpHandler));
Type staticFileHandlerType = assembly.GetType("System.Web.StaticFileHandler");
ConstructorInfo constructorInfo = staticFileHandlerType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
return (IHttpHandler) constructorInfo.Invoke(null);

그러나 내부 유형을 사용하는 것은 적절한 해결책이 아닌 것 같습니다. 또 다른 옵션은 내 자신 StaticFileHandler의을 구현 하는 것이지만 제대로 수행하는 것 (범위 및 etag와 같은 HTTP 항목 지원)은 사소하지 않습니다.

ASP.NET에서 정적 파일의 라우팅에 어떻게 접근해야합니까?


몇 시간 동안이 문제를 조사한 후 무시 규칙을 추가하는 것만으로도 정적 파일이 제공된다는 것을 알았습니다.

RegisterRoutes (RouteCollection 경로)에서 다음 무시 규칙을 추가합니다.

routes.IgnoreRoute("{file}.js");
routes.IgnoreRoute("{file}.html");

IIS를 사용하지 않는 이유는 무엇입니까? 요청이 애플리케이션에 도달하기 전에 첫 번째 경로에서 두 번째 경로로 모든 요청을 가리키는 리디렉션 규칙을 만들 수 있습니다. 이 때문에 요청을 리디렉션하는 더 빠른 방법입니다.

IIS7 +가 있다고 가정하면 다음과 같은 작업을 수행합니다.

<rule name="Redirect Static Images" stopProcessing="true">
  <match url="^static/?(.*)$" />
  <action type="Redirect" url="/a/b/c/{R:1}" redirectType="Permanent" />
</rule>

또는 @ ni5ni6에서 제안한대로 리디렉션 할 필요가없는 경우 :

<rule name="Rewrite Static Images" stopProcessing="true">
  <match url="^static/?(.*)$" />
  <action type="Rewrite" url="/a/b/c/{R:1}" />
</rule>

@RyanDawkins에 대해 2015-06-17 수정 :

그리고 재 작성 규칙이 어디로 가는지 궁금하다면 여기 web.config파일 에서의 위치 맵이 있습니다.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <!-- rules go below -->
        <rule name="Redirect Static Images" stopProcessing="true">
          <match url="^static/?(.*)$" />
          <action type="Redirect" url="/a/b/c/{R:1}" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

I've had a similar problem. I ended up using HttpContext.RewritePath:

public class MyApplication : HttpApplication
{
    private readonly Regex r = new Regex("^/static/(.*)$", RegexOptions.IgnoreCase);

    public override void Init()
    {
        BeginRequest += OnBeginRequest;
    }

    protected void OnBeginRequest(object sender, EventArgs e)
    {
        var match = r.Match(Request.Url.AbsolutePath);
        if (match.Success)
        {
            var fileName = match.Groups[1].Value;
            Context.RewritePath(string.Format("/a/b/c/{0}", fileName));
        }
    }
}

I came up with an alternative to using the internal StaticFileHandler. In the IRouteHandler I call HttpServerUtility.Transfer:

public class FileRouteHandler : IRouteHandler {

  public IHttpHandler GetHttpHandler(RequestContext requestContext) {
    String fileName = (String) requestContext.RouteData.Values["file"];
    // Contrived example of mapping.
    String routedPath = String.Format("/a/b/c/{0}", fileName);
    HttpContext.Current.Server.Transfer(routedPath);
    return null; // Never reached.
  }

}

This is a hack. The IRouteHandler is supposed to return an IHttpHandler and not abort and transfer the current request. However, it does actually achieve what I want.

Using the internal StaticFileHandler is also somewhat a hack since I need reflection to get access to it, but at least there is some documentation on StaticFileHandler on MSDN making it a slightly more "official" class. Unfortunately I don't think it is possible to reflect on internal classes in a partial trust environment.

I will stick to using StaticFileHandler as I don't think it will get removed from ASP.NET in the foreseeable future.


You need to add TransferRequestHandler for handling your static files.Please see following answer https://stackoverflow.com/a/21724783/22858

참고URL : https://stackoverflow.com/questions/1149750/using-asp-net-routing-to-serve-static-files

반응형