0

405 errorI am trying to download an excel file from WEB API Get method of type HttpResponseMessage. I am able to hit the method by making an AJAX call, the method also returns a resultcontent, but it's not downloading the file on the browser. I tried window.location, it redirects to a new page saying - 'The website cannot display the page'. I tried to debug by alerting in success & error, it alerts in error as [Object object]. Below is my code, please correct where I am going wrong. Thanks.

JavaScript

$(document).ready(function () {
    $("#btnDownload").click(function () {        
        var apiUrl = "../api/DownloadExcel/ExportExcelFile?OriginalRequestNumber=";
        var originalReqIdentifier = $('#OriginalRequestNumber').val();
        $.ajax({
            url: apiUrl + originalReqIdentifier,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert('hi');
            }
        });
    });
});

HTML

<input href="#" class="btn" type="Submit" id="btnDownload" name="btnDownload" value="Download" />

c#

    public class DownloadExcelController : ApiController
{
    private IExcelExport _excelExport { get; set; }

    public DownloadExcelController()
    {
        _excelExport = new GenerateExcel();
    }
// GET api/DownloadExcel/ExportExcelFile
    [HttpGet]       
    public HttpResponseMessage ExportExcelFile(string OriginalRequestNumber)
    {
        var ObjectToExcel = new List<DummyExternalLoginViewModel>
        {
            new DummyExternalLoginViewModel { Name = "Mohammed", FamilyName= "Ansari", State = "CA"},
            new DummyExternalLoginViewModel { Name = "Harvey", FamilyName= "Spectre", State = "NY"},
            new DummyExternalLoginViewModel { Name = "Mike", FamilyName= "Ross", State = "NY"},
            new DummyExternalLoginViewModel { Name = "Donald", FamilyName= "Trump", State = "AL"},
            new DummyExternalLoginViewModel { Name = "Spencer", FamilyName= "Mike", State = "AK"},
            new DummyExternalLoginViewModel { Name = "Trump", FamilyName= "Donald", State = "AZ"},
            new DummyExternalLoginViewModel { Name = "Bill", FamilyName= "Gates", State = "AR"}
        };
        var resultContent = _excelExport.Export(ObjectToExcel, "ExcelExport", true);

        return resultContent;
    }  
 }
Indhi
  • 1,684
  • 5
  • 27
  • 48

2 Answers2

1

You have issues on both sides - client & server ones:

Use sync file download (or async as described Download a file by jQuery.Ajax):

$(document).ready(function () {
    $("#btnDownload").click(function () {        
        var apiUrl = "../api/DownloadExcel/ExportExcelFile?OriginalRequestNumber=";
        var originalReqIdentifier = $('#OriginalRequestNumber').val();

        window.location = apiUrl + originalReqIdentifier;
    });
});

Define the required properties of HttpResponseMessage:

[HttpGet]       
public HttpResponseMessage ExportExcelFile(string OriginalRequestNumber)
{
    // ..
    var resultContent = _excelExport.Export(ObjectToExcel, "ExcelExport", true);

    var stream = new MemoryStream(resultContent);

    var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) };

    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "file.xlsx" };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");

    return response;
} 
vladimir
  • 13,428
  • 2
  • 44
  • 70
  • These response lines are already defined inside the Export method. A new window is opened with an error - This error (HTTP 405 Method Not Allowed) means that Internet Explorer was able to connect to the website, but the site has a programming error. – Indhi Dec 16 '19 at 15:16
  • please see the attached error image on browser inspecting – Indhi Dec 16 '19 at 15:38
0
<script>
$(document).ready(function () {
    $("#btnDownload").click(function () {        
        var apiUrl = "../api/DownloadExcel/ExportExcelFile?OriginalRequestNumber=";
        var originalReqIdentifier = $('#OriginalRequestNumber').val();          
        $.ajax({
            url: apiUrl + originalReqIdentifier,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                window.location = apiUrl + originalReqIdentifier;
            }
        });
    });
});
</script>

placing window.location = apiUrl + originalReqIdentifier; in Ajax error, worked for me.

Indhi
  • 1,684
  • 5
  • 27
  • 48