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

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

Related

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

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

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

Internal Server Error 500 on async upload asp mvc 5

Just started using ASP.Net 4.5 and my API always returns Internal Server Error.
Upload API
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> PostFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data/uploads/");
var provider = new CustomMultipartFormDataStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
My Controller
var message = new HttpRequestMessage();
var content = new MultipartFormDataContent();
message.Method = HttpMethod.Post;
message.Content = content;
message.RequestUri = new Uri("http://localhost:12345/api/upload/");
var client = new HttpClient();
client.SendAsync(message).ContinueWith(task =>
{
var result = task.Result.ReasonPhrase;
if (task.Result.IsSuccessStatusCode)
{
//do something
}
});
The files are saved in the location (/App_Data/uploads/) but why is the status code always 500?
Please enlighten me. Thanks
Here is part of working controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Product product, HttpPostedFileBase file)
{
if (!ModelState.IsValid)
return PartialView("Create", product);
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var guid = Guid.NewGuid().ToString();
var path = Path.Combine(Server.MapPath("~/Content/Uploads/ProductImages"), guid + fileName);
file.SaveAs(path);
string fl = path.Substring(path.LastIndexOf("\\"));
string[] split = fl.Split('\\');
string newpath = split[1];
string imagepath = "Content/Uploads/ProductImages/" + newpath;
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
var nId = Guid.NewGuid().ToString();
// Save record to database
product.Id = nId;
product.State = 1;
product.ImagePath = imagepath;
product.CreatedAt = DateTime.Now;
db.Products.Add(product);
await db.SaveChangesAsync();
TempData["message"] = "ProductCreated";
//return RedirectToAction("Index", product);
}
// after successfully uploading redirect the user
return Json(new { success = true });
}

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