Not Able to Download file from MVC Web API

Soni Samuel Panackacheril 61 Reputation points
2020-10-08T08:35:35.72+00:00

Hi,

I am trying to download a file using MVC Web API, where I am facing two issues.

First, I am Getting the CORS error,
Access to XMLHttpRequest at 'http://testservices.lab.com/api/DYRDSP/GetSignatureImage/35/01/1werw12' from origin 'http://testwebapp.lab.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Secondly I am not getting any response/output. I am pasting my code. Appreciate some insight on what I am doing wrong.

In HTML, from Web Application Client ASPX Page
<a href="http://testservices.lab.com/api/DYRDSP/GetSignatureImage/35/01/1werw12">Download Signature</a>

In Web API Controller
[HttpGet, HttpOptions]
[Route("api/DYRDSP/GetSignatureImage/{userId}/{signatureImageTypeId}/{sessionToken}")]
public HttpResponseMessage GetSignatureImage(string userId, int signatureImageTypeId, string sessionToken)
{

        System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
        System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
        System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

        HttpResponseMessage responseMsg = Request.CreateResponse(HttpStatusCode.OK);

        string myFilePath = (new DAL.KSMDAL()).GetEmpolyeeSignature(userId, signatureImageTypeId);
        string myFileName = Path.GetFileName(myFilePath);

        //Check whether File exists.
        if (!File.Exists(myFilePath))
        {
            //Throw 404 (Not Found) exception if File not found.
            responseMsg.StatusCode = HttpStatusCode.NotFound;
            responseMsg.ReasonPhrase = string.Format("File not found in : {0} .", myFilePath);
            throw new HttpResponseException(responseMsg);
        }
        else
        {
            //Read the File into a Byte Array.
            byte[] bytes = File.ReadAllBytes(myFilePath);

            MemoryStream memStream = new MemoryStream(bytes);

            //Set the Response Content.
            responseMsg.Content = new StreamContent(memStream);// new ByteArrayContent(bytes);

            var headers = responseMsg.Content.Headers;
            headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            headers.ContentDisposition.FileName = myFileName;
            headers.ContentType = new MediaTypeHeaderValue("applications/jpg"); 
            headers.ContentLength = memStream.Length;
        }                    

        return responseMsg;

    }
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
38,551 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tianyu Sun-MSFT 30,326 Reputation points Microsoft Vendor
    2020-10-09T01:32:00.007+00:00

    Hi Soni,

    Thank you for taking time to post this issue in Microsoft Q&A forum. MVC and Web API are currently not supported in the Microsoft Q&A forums, the supported products are listed over here: https://learn.microsoft.com/en-us/answers/products/ (more to be added later on).

    For the related questions about MVC, you can post here: ASP .NET Community(MVC) and for the related questions about Web API, you can post here: ASP .NET Community(Web API).

    Thanks for your understanding.

    Best Regards,
    Tianyu

    • If the answer is helpful, please click "Accept Answer" and upvote it.
      Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.