How to read application/pdf type from web api and display the response in browser in asp.net c#? - asp.net

I have a Web API which returns HttpResponseMessage of type application/pdf using HttpPost method. I want to display the file which is returning from the API in asp.net webforms but I am unable to do it even though I tried to return response directly. Can anyone help me. P.S:-When I pass parameters in body using Postman Post I am able to generate PDF.
Web API Code:-
public HttpResponseMessage o([FromBody] CPRSsubmit customers)
{
string path = "~/PayBill/" + customers.value + "/";
string sail_pl_no;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
using (OracleConnection con = new OracleConnection(ConnectionStr.Con("oracle")))
{
using (OracleCommand cmd = new OracleCommand(query, con))
{
cmd.Connection = con;
con.Open();
using (OracleDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
while (sdr.Read())
{
sail_pl_no = Convert.ToString(sdr[0]).Trim();
path += sail_pl_no;
}
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
con.Close();
}
}
path += "_E_" + customers.value + ".pdf";
string filePath = HttpContext.Current.Server.MapPath(path);
if (!File.Exists(filePath))
{
//Throw 404 (Not Found) exception if File not found.
response.StatusCode = HttpStatusCode.NotFound;
response.ReasonPhrase = string.Format("File not found");
throw new HttpResponseException(response);
}
byte[] bytes = File.ReadAllBytes(filePath);
response.Content = new ByteArrayContent(bytes);
response.Content.Headers.ContentLength = bytes.LongLength;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
response.Content.Headers.ContentDisposition.FileName = customers.value + ".pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(customers.value + ".pdf"));
return response;
}
Asp.net webform code:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
Model.CPRSPost cpr = new Model.CPRSPost();
cpr.pl_no = Convert.ToInt32(Session["LoginId"]);
cpr.value = ddlMonth.SelectedValue;
var url = "CPRSPayBill/O";
HttpResponseMessage response = client.PostAsJsonAsync(url,cpr).Result;
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
}
}

Related

What can i do if SSL certificate don`t working in IIS, but working in Local

I have two projects: Web Api(back) and MVC(front). Web Api(back) has a method that uses the SSL certificate. If running the Web Api(back) in local, then the method works, but if running Web Api(back) in IIS and send post in MVC(front) to the method, then it catches an error "One or more errors occurred". (The SSL connection could not be established, see inner exception.).
Web Api(back) code
public decimal GetIdentification(IdentificationModel identification, int key)
{
try
{
var handler = new HttpClientHandler();
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"cert\\hgg.p12");
handler.ClientCertificates.Add(new X509Certificate2(path, _certPassword));
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), _identityUrl + "iin=" + identification.IIN + "&vendor=" + _vendor))
{
string token = GetToken();
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
request.Headers.TryAddWithoutValidation("x-idempotency-key", "key:" + "hggKey-" + key);
request.Method = new HttpMethod("POST");
//request.Content = new StringContent(identification.Photo);
request.Content = new StreamContent(new MemoryStream(Convert.FromBase64String(identification.Photo)));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
var response = httpClient.SendAsync(request);
string data = response.Result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<dynamic>(data).result;
}
}
}
catch (Exception e)
{
throw new Exception("GetIdentification" + e.Message);
}
}
public string GetToken()
{
var handler = new HttpClientHandler();
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cert\\hgg.p12");
handler.ClientCertificates.Add(new X509Certificate2(path, _certPassword));
try
{
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), _tokenUrl))
{
request.Headers.TryAddWithoutValidation("Authorization", "Basic " + _token);
request.Method = new HttpMethod("POST");
request.Content = new StringContent("grant_type=password&username=" + _username + "&password=" + _password + "&scope=identkey");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = httpClient.SendAsync(request);
return JsonConvert.DeserializeObject<dynamic>(response.Result.Content.ReadAsStringAsync().Result).access_token;
}
}
}
catch(Exception e)
{
throw new Exception("GetToken" + e.Message + path + " " +_certPassword);
}
}
}
MVC(front)
public string Identity(RequestClass<IdentificationModel> request)
{
ResponseClass<decimal> response = new ResponseClass<decimal>();
using (var httpClient = new HttpClient())
{
var json = JsonConvert.SerializeObject(request);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse =
httpClient.PostAsync(_apiUrl + $"Identification", data).Result;
string responseContent = httpResponse.Content.ReadAsStringAsync().Result;
return responseContent;
}
}
ApplicationPoolIdentity don't have permission for certmgr.msc

ASP.NET WEB API cant upload multipart/form-data (image) to Web server

After uploading image through ASP.NET WEB API successfuly through localhost . I uploaded my project to the hosting server but this time i got the error as
an error has occured
This is my controller
tutorEntities entities = new tutorEntities();
[HttpPost]
public HttpResponseMessage ImageUp()
{
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
img std = new img();
// std.Title = httpContext.Request.Form["Title"];
// std.RollNo = httpContext.Request.Form["RollNo"];
// std.Semester = httpContext.Request.Form["Semester"];
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
string random = Guid.NewGuid().ToString();
string url = "/UserImage/" + random + httpRequest.Files[0].FileName.Substring(httpRequest.Files[0].FileName.LastIndexOf('.'));
Console.WriteLine(url);
string path = System.Web.Hosting.HostingEnvironment.MapPath(url);
httpRequest.Files[0].SaveAs(path);
std.Path = "http://localhost:2541/" + url;
}
entities.imgs.Add(std);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
Ensure that AppPoolIdentity user has write permissions on the UserImage folder. Also, catch the exception in code for debugging:
try {
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
img std = new img();
// std.Title = httpContext.Request.Form["Title"];
// std.RollNo = httpContext.Request.Form["RollNo"];
// std.Semester = httpContext.Request.Form["Semester"];
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
string random = Guid.NewGuid().ToString();
string url = "/UserImage/" + random + httpRequest.Files[0].FileName.Substring(httpRequest.Files[0].FileName.LastIndexOf('.'));
Console.WriteLine(url);
string path = System.Web.Hosting.HostingEnvironment.MapPath(url);
httpRequest.Files[0].SaveAs(path);
std.Path = "http://localhost:2541/" + url;
}
entities.imgs.Add(std);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception ex) {
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(ex.ToString()),
ReasonPhrase = "Error"
}
throw new HttpResponseException(response);
}

Odata naming file return error message of the

I have this custom Odata function to download pdf from download pdf database. I have some issues
1.with Pdf name does not name "reportname.pdf" it is named response.pdf as
2.return error message of reportBinary is null
[HttpGet]
[ODataRoute("GetDownloadReport(downloadId={downloadId})")]
public HttpResponseMessage GetDownloadReport(Guid downloadId)
var received = DateTime.UtcNow;
byte[] reportBinary = null;
string queryString = "SELECT report FROM downloads WHERE id = #downloadId ";
bool success = false;
using (SqlConnection conn = new SqlConnection(connectionString))
{
//get the binary from database
}
HttpResponseMessage response = null;
try
{
if (reportBinary == null)
return Request.CreateResponse(HttpStatusCode.Gone);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(reportBinary);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = "PORTName.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
}
try to set filename manually:
String headerInfo = "attachment; filename=" + System.Web.HttpUtility.UrlPathEncode("PORTName.pdf");
response.Content.Headers.Add("Content-Disposition", headerInfo);
I'm not sure what do you want to do about error message, but if you mean setting string content, just set it ;)
response = Request.CreateResponse(HttpStatusCode.Gone);
response.Content = new StringContent(...);
return response;
Consider using NotFound instead of Gone status code (Gone has very specific meaning).

How to upload a file on a server through api call in asp.net mvc

public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
WebClient webClient = new WebClient();
byte[] responseBinary = webClient.UploadFile(apiUrl, file.FileName);
string response = Encoding.UTF8.GetString(responseBinary);
/* Giving error here. How to proceed?
}
I want to upload a single file to this url and the response is shown in the figure above. How to proceed further with the same in C#? Please help
Try your code like below.
public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
using (HttpClient client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] fileBytes = new byte[file.InputStream.Length + 1];
file.InputStream.Read(fileBytes, 0, fileBytes.Length);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var result = client.PostAsync(apiURL, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
return new
{
code = result.StatusCode,
message = "Successful",
data = new
{
success = true,
filename = file.FileName
}
};
}
else
{
return new
{
code = result.StatusCode,
message = "Error"
};
}
}
}
}

Google voice call error

namespace GoogleVoiceCall
{
class Program
{
private const string LOGIN_URL = "https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral";
private const string GOOGLE_VOICE_HOME_URL = "https://www.google.com/voice";
private const string CALL_URL = "https://www.google.com/voice/call/connect";
private static string m_emailAddress = "your email address";
private static string m_password = "password";
private static string m_gizmoNumber = "your gizmo number";
private static string m_destinationNumber = "your destination number";
static void Main(string[] args)
{
try
{
Console.WriteLine("Attempting Google Voice Call");
CookieContainer cookies = new CookieContainer();
// First send a login request to get the necessary cookies.
string loginData = "Email=" + Uri.EscapeDataString(m_emailAddress)
+ "&Passwd=" + Uri.EscapeDataString(m_password);
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
loginRequest.CookieContainer = cookies;
loginRequest.AllowAutoRedirect = true;
loginRequest.Method = "POST";
loginRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
loginRequest.ContentLength = loginData.Length;
loginRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(loginData), 0, loginData.Length);
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
if (loginResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("Login failed.");
}
else
{
Console.WriteLine("Login request was successful.");
}
// Second send a request to the Google Voice home page to get a string key needed when placing a callback.
HttpWebRequest keyRequest = (HttpWebRequest)WebRequest.Create(GOOGLE_VOICE_HOME_URL);
keyRequest.CookieContainer = cookies;
HttpWebResponse keyResponse = (HttpWebResponse)keyRequest.GetResponse();
if (keyResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("_rnr_se key request failed.");
}
else
{
Console.WriteLine("Key request was successful.");
}
StreamReader reader = new StreamReader(keyResponse.GetResponseStream());
string keyResponseHTML = reader.ReadToEnd();
Match rnrMatch = Regex.Match(keyResponseHTML, #"name=""_rnr_se"".*?value=""(?<rnrvalue>.*?)""");
if (!rnrMatch.Success)
{
throw new ApplicationException("_rnr_se key was not found on your Google Voice home page.");
}
string rnr = rnrMatch.Result("${rnrvalue}");
Console.WriteLine("_rnr_se key=" + rnr);
// Thirdly (and lastly) submit the request to initiate the callback.
string callData = "outgoingNumber=" + Uri.EscapeDataString(m_destinationNumber) +
"&forwardingNumber=" + Uri.EscapeDataString(m_gizmoNumber) +
"&subscriberNumber=undefined&remember=0&_rnr_se=" + Uri.EscapeDataString(rnr);
HttpWebRequest callRequest = (HttpWebRequest)WebRequest.Create(CALL_URL);
callRequest.CookieContainer = cookies;
callRequest.Method = "POST";
callRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
callRequest.ContentLength = callData.Length;
callRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(callData), 0, callData.Length);
HttpWebResponse callResponse = (HttpWebResponse)callRequest.GetResponse();
if (callResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Call request failed.");
}
else
{
Console.WriteLine("Call request was successful.");
}
}
catch (Exception excp)
{
Console.WriteLine("Exception Main. " + excp.Message);
}
finally
{
Console.WriteLine("finished, press any key to exit...");
Console.ReadLine();
}
}
}
}
I have used the above codes for make a call like Googl voice call using Google voicall service, but i am getting an error. error is
_rnr_se key was not found
pelase tell here what are this
m_gizmoNumber and _rnr_se key
add this line before login request :
m_cookies.Add(new Uri(PRE_LOGIN_URL), galxResponse.Cookies);
see here .

Resources