.net Website throws 404 error - asp.net

I've got a working website that I can upload and download files to a folder within the project locally. However when I use IIS to host the website across LAN, I get a 404 error when trying to download files - I can upload the files fine and they appear in the correct folder.
Error:
HTTP Error 404.0 - Not Found The resource you are looking for has been
removed, had its name changed, or is temporarily unavailable.
Here are my controllers.
Download controller:
[HttpGet]
public virtual ActionResult Download(string file)
{
string fullPath = Path.Combine(Server.MapPath("~/SupportAttachments/"), file);
return File(fullPath, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", file);
}
Upload Controller:
[HttpPost]
public JsonResult UploadFiles(string id)
{
try
{
foreach (string file in Request.Files)
{
var hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = id + " " + hpf.FileName;
var path = Path.Combine(Server.MapPath("~/SupportAttachments/"), Path.GetFileName(fileName));
// Save the file
hpf.SaveAs(path);
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return this.Json("Upload failed");
}
return this.Json("File uploaded successfully");
}
Can anyone advise me as to why I can't download files when hosting via IIS?

Related

access is denied when trying to upload image to the server using asp.net web api 2

I am trying to upload image to the server with WebAPI
C# Code:
public async Task<string> Post()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach(string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filename = postedFile.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var filePath = HttpContext.Current.Server.MapPath("~/Uploads/"+ filename);
postedFile.SaveAs(filePath);
return "/uploads" + filename;
}
}
else
{
return "file was not uploaded";
}
}
catch (Exception exception)
{
return exception.Message;
}
return "hi";
}
When I upload image through postman, I get
"Access to the path 'c:\users\ahmed\source\repos\Election\Election\Uploads\Background.png' is denied."
Check your upload folder permissions. And add everyone permission to upload folder, and test it again. Don't forget remove everyone permission when test is over.

ASP.NET Core RC-1 file upload

I am currently uploading a file via the kendo fileuploader to an api controller using ASP.NET core RC-1. I am receiving a periodic error of "object reference not set to instance of object" when attempting to read the stream following opening the stream with IFormFile.OpenReadStream().
My controller is:
[HttpPost]
[Route("api/{domain}/[controller]")]
public async Task<IActionResult> Post([FromRoute]string domain, [FromForm]IFormFile file, [FromForm]WebDocument document)
{
if (ModelState.IsValid)
{
if (file.Length > 0)
{
var userName =
Request.HttpContext.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypesEx.FullName)?
.Value;
var uploadedFileName =
ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
document.Domain = domain;
document.MimeType = file.ContentType;
document.SizeInBytes = file.Length;
document.ChangedBy = userName;
document.FileName = (string.IsNullOrEmpty(document.FileName)) ? uploadedFileName : document.FileName;
try
{
document = await CommandStack.For<WebDocument>()
.AddOrUpdateAsync(document, file.OpenReadStream()).ConfigureAwait(false);
}
catch (Exception e)
{
return new HttpStatusCodeResult(500);
}
return Ok(document);
}
}
return new BadRequestResult();
}
And the error is being thrown when I actually try to read the stream when it is going into blob storage:
public async Task<Uri> CreateOrUpdateBlobAsync(string containerName, string fileName, string mimeType,
Stream fileStream)
{
var container = Client.GetContainerReference(containerName);
var blob = container.GetBlockBlobReference(fileName);
//Error HERE
await blob.UploadFromStreamAsync(fileStream);
blob.Properties.ContentType = mimeType;
await blob.SetPropertiesAsync();
return blob.Uri;
}
What I am having trouble with is this is sporadic and there seems to be no defined pattern of which files are accepted and which ones generate the error. At first I thought it might be a size issue but that is not the case as I have several larger files uploaded successfully and then one small file will throw the error. Images seem to work fine and it is hit or miss on other file types with no rhyme or reason that I can figure out.

File Upload : ApiController

I have a file being uploaded using http post request using multipart/form-data to my class that is extending from ApiController.
In a dummy project, I am able to use:
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase
to get the file inside my controller method where my Request is of type System.Web.HttpRequestWrapper.
But inside another production app where I have constraints of not adding any libraries/dlls, I don't see anything inside System.Web.HttpRequestWrapper.
My simple requirement is to get the posted file and convert it to a byte array to be able to store that into a database.
Any thoughts?
This code sample is from a ASP.NET Web API project I did sometime ago. It allowed uploading of an image file. I removed parts that were not relevant to your question.
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
var firstImage = provider.Contents.FirstOrDefault();
if (firstImage == null || firstImage.Headers.ContentDisposition.FileName == null)
return Request.CreateResponse(HttpStatusCode.BadRequest);
using (var ms = new MemoryStream())
{
await firstImage.CopyToAsync(ms);
var byteArray = ms.ToArray();
}
return Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}

Error to upload file to Amazon S3 for a ASP MVC application

Here is the controller.
I need to upload a image to AWS S3 but I'm get a error . I'm using the MVC project for asp application.
[HttpPost, ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Nueva(Historia historia, HttpPostedFileBase HeroImagen)
{
try
{
if (ModelState.IsValid)
{
IAmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey))
{
var request = new PutObjectRequest()
{
BucketName = _bucketName,
CannedACL = S3CannedACL.PublicRead,
Key = string.Format("UPLOADS/{0}", HeroImagen.FileName),
InputStream = HeroImagen.InputStream
};
client.PutObject(request);
}
historia.HeroImagen = HeroImagen.FileName;
db.Historias.Add(historia);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AutorID = new SelectList(db.Autores, "AutorID", "AutorNombre", historia.AutorID);
return View(historia);
}
catch (Exception)
{
return View();
}
}
But, when I submit the form get an error.
.
For me it look like your AWS related code is not even running.
You get an error based on the line "Viewbag.AutorID = ...", which means, the redirect command above it was never running. For me it looks like your ModelState is invalid.
Note: Please copy your code and exception to your question as text, that would make your question searchable.

.ashx HTTP handler unable to write image from network share to HTTP response

I am trying to write an HTTP handler in C# that loads images from a network drive and writes them to the HTTP response. This is currently not working for me as I keep getting HTTP 302 responses which results in the broken file image being displayed. Below is my HTTP handler. Access permissions have been set so anonymous users have read access to the share but ideally this will not be permanent.
public class SecCamImage : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
KeyValueConfigurationElement setting = null;
if(config.AppSettings.Settings.Count > 0)
{
setting = config.AppSettings.Settings["CameraBaseURL"];
}
if(setting != null)
{
string baseURL = setting.Value;
string location = context.Request["location"].ToString();
string camera = context.Request["camera"].ToString();
string image = context.Request["image"].ToString();
if (!(string.Compare(image, "no-image.jpg", true) == 0))
{
if (!string.IsNullOrEmpty(location) && !string.IsNullOrEmpty(camera) && !string.IsNullOrEmpty(image))
{
string fullPath = string.Format(baseURL, location, camera, image);
System.IO.FileInfo imageFile = new System.IO.FileInfo(fullPath);
if (imageFile.Exists)
{
if (context.User.Identity.IsAuthenticated)
{
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(imageFile.FullName);
context.Response.End();
}
}
}
}
else
{
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(image);
context.Response.End();
}
}
}
public bool IsReusable
{
get { return false; }
}
}
The URL stored in the config file is structured like this:-
\\\\host\\directory\\{0}\\{1}\\{2}
{0} and {1} are directories and {2} is the file.
I managed to get this working by adding a Virtual Directory to our Website on IIS. The .ashx handler now references the Virutal Directory and not the directory on the network drive.

Resources