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;
}