Quickly deliver a text file to the user - API Controller C#

After spending several hours searching and struggling to prompt a download of a text file from the server to the User's machine, I've decided to seek help here. The function is located in an ApiController.

public class LogViewerController : ApiController

Below is the code for the function:

public void Get()
    {
        try
        {
            string path = @"C:\TestDocument.txt";

            var context = HttpContext.Current;
            context.Response.Clear();
            context.Response.ContentType = "application/octet-stream";
            context.Response.AddHeader("Content-Disposition", "attachment; filename="Test");

            context.Response.WriteFile(path);

            context.Response.End();
        }
        catch (Exception e)
        {
            //
        }
    }

The goal is to retrieve the file at the specified path and prompt the user to download/save it. However, instead of downloading, the file content is being printed out in '#textField'.

Here is the Javascript/ajax code:

$.ajax({
        cache: false,
        type: 'GET',
        url: '@ViewBag.servicesUrl/LogViewer',
        datatype: 'JSON',
        success: function (retdata) {
            $('#textField').html(retdata);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //
        },
    });

I am puzzled by what might be causing this issue. Could it be related to the fact that it's within a GET request?

This is my first time posting a question here. Please let me know if further information is needed. Thank you for any assistance!

Answer №1

Instead of relying on AJAX to download a file, it's better to simply include a link to a controller route or URL that will execute the existing server-side code you have in place.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most efficient method for conditionally rendering components in React?

I'm currently in a dilemma about how to render a component based on a certain condition in React. Which way is considered the best practice? Your expertise would greatly assist me as I navigate through this decision-making process. First approach: co ...

Mastering the art of switching between different application statuses in ReactJS

As a newcomer to reactJS, I am exploring ways to make one of my components cycle through various CRUD states (creating object, listing objects, updating objects, deleting objects). Each state will correspond to displaying the appropriate form... I have co ...

Animating the scaling of a cube along the Y-axis using WebGL and Three.js

Experiencing Unexpected Results with Tween in Webgl Three.js and JavaScript var scale = {y:0}; var tween = new TWEEN.Tween( cube.scale.y ).to( { y: 10 }, 3000 ).easing( TWEEN.Easing.Cubic.Out ).start(); I am attempting to animate the stretchi ...

Adjust the size of the text and save it in a cookie for later use

I am in need of a script that can dynamically increase and decrease the font size on a website while retaining the user's chosen setting even after they return to the site. I believe utilizing cookies is the way to achieve this functionality. Despite ...

What category does Ajax fall under in terms of scripting: client-side or server-side

Does Ajax fall under client-side or server-side scripting? ...

What are the steps to designing a unique JSON data format?

When working with a JSON data structure containing 100 objects, the output will resemble the following: [{ "Value": "Sens1_001", "Parent": Null, "Child": { "Value": "Sens2_068", "Parent":"Sens1_001", "Child" : { ...

How to effectively manage time and regularly execute queries every second using Node.js?

Currently working on developing a web software using node js with an Mssql database. There is a table in the database that includes a datetime value and a bit value. The bit value remains at 0 until the real-time matches the datetime value, at which point ...

Blazor components experience element interaction while utilizing more than one instance of Blazorise.Bootstrap component

I am facing an issue in my Blazor app where a component with a button and bootstrap collapse works fine when used once on a page, but triggers collapse elements in other instances when used multiple times. This seems to be happening because their IDs are s ...

Exploring varying approaches to submitting an HTML form

I'm attempting to create an HTML document that performs the following tasks: It gathers a group of form fields with a shared name and sends them to a file called "delete.py," then it collects another set of form fields and transmits those values to "t ...

Remove parent-child relationships in databases using SQL or JavaScript iterations

Currently working with postgresql, I'm trying to figure out a method for recursively deleting rows along with their child rows. This involves either using SQL or JavaScript loops. For example, if I want to delete TagId: 0, I also need to delete rela ...

Choose not to alter the display value during keyup and keydown events, while still triggering the change event

$(function(){ $(".cls_user_details select").keyup(function(){ $(".cls_user_details select").val("Profile"); }) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cls_user_setti ...

What is the best way to eliminate opacity in an element using react dnd?

When I use react-dnd to drag an item, the element being dragged becomes almost completely opaque. I would like to increase its visibility, is there a way to achieve this? In the image below, the upper element is the one being dragged and the bottom one is ...

Confidential data in Module Design

I'm curious about the concept of private variables in JavaScript. How is it that I can still access a private variable through a public method and redefine the properties of the module? For example: var aModule = (function() { var privateVar = 1 ...

Navigating to an offline HTML webpage using JavaScript in a PhoneGap application

I am currently developing a phonegap application. I am attempting to create a login feature where upon clicking the submit button on the Login.html page, I should be directed to a local HTML file. Login.html <tr> <td>&nbsp;</td> ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Which is better for testing in Cypress: classes or functions?

When it comes to testing in Cypress, which approach do you believe is more efficient? Functions: 'support/pages/login.js' export const login = (username, password) => { cy.get('#username').type(username); cy.get(& ...

Angular 2 table fails to refresh after callback updates collection, but a timer update triggers a full refresh of the collection

I am experiencing an issue with updating a string[] collection from the Observable subscription: heroes:string[] = ['milan']; // this works fine let current = this; (function theLoop (i: number) { setTimeout(() => { current.heroe ...

I want to customize my Google Apps Script to only target specific cells, not all cells

I need help with a script that changes the currency symbol within specific cells based on user selection. Currently, the script is applied to all cells but I only want it to affect cells C9, C12, and C13. I'm not sure where to make this adjustment in ...

Tips for transforming tabular text into JSON format with nodejs?

I am currently working with node.js and looking to transform the provided string: 13 0.02 23 0.11 0.15 37 AIRLINES 74 0.02 343 0.08 0.23 708 ALL CLOTHING STORES 211 0.02 127 0.02 0.03 386 ...

What is the best approach to prevent the need for repeatedly specifying a parameter in each controller

I am trying to figure out a way to prevent redundant code by passing Request.Headers into every service method. [HttpGet] [Route("accounts({id:guid})")] [Route("accounts")] public async Task<HttpResponseMessage> GetAccount() { ...