How to edit single static file during serving it to client in ASP .NET Core?

Viewed 85

I have MVC Core application with Angular. I need to provide one file xyz.json to client but edit it. This file exists physically. I just need to edit few parts of it with dynamic information.

I was thinking about middleware that would inject information into that one specific file. But I'm not sure if this is correct way to do it.

1 Answers

I've used a controller action to create a dedicated endpoint for this kind of scenario. In the action, you can read the content from the file and modify it, then return as either a FileContentResult or ContentResult. For example:

[HttpGet("xyz-stuff")]
public IActionResult Xyz()
{
    var path = Path.Combine(environment.WebRootPath, "xyz.json");
    string rawContent = System.IO.File.ReadAllText(path);

    // Modify raw content
    string modifiedContent = "...";

    // Serve modified content
    return Content(modifiedContent, "application/json");
}

Depending on how dynamic the changes are, you may want to cache the result in order to avoid the read/modify operations on every request.

Related