简体   繁体   中英

Server.MapPath in ashx?

I have an ashx file that serves PDF documents. Our environment is we develop locally, and the web app is moved to different environments: test and then production.

What is the best way to access a path on the server? How can I use Server.MapPath() in an .ashx handler.

You can access the Server through the HttpContext .

public void ProcessRequest(HttpContext context) {

    context.Server.MapPath(...);
}

I'd like to add another case to the scenario

Case one:

For example if you know the path to deploy and this isn't under the context of your application: from VS 2010 you can add a web.config transform depending on your build configuration

to keep it simple you can have a web.debug.config (let's assume development) and web.release.config (production) or you can set up your own build configuration as web.production.config if you want.

you can create an application setting for referencing the full path of the folder and do a transformation depending on which environment you are going to deploy

something like

<appSettings>
    <add key="folderPath" value="c:\dev" />
    // other keys here
</appSettings>

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add key="folderPath" value="c:\production" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
  </appSettings>
</configuration>

Case two: using the server mapPath as you mentioned

System.Web.HttpContext.Current.Server.MapPath() or context.Server.MapPath() 

If the PDF files are stored in a subdirectory of the one where your ashx is stored, you could use ~ as the root of your application:

public void ProcessRequest (HttpContext context) {
// ...
    context.Response.WriteFile("~/PDFs/onefile.pdf");
}

if your files are in a physical folder that is not a virtual directory, you could store the path in Web.Config (with a different configuration in dev, test and production)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM