Can an ASP.NET MVC controller return an Image?

Use the base controllers File method. public ActionResult Image(string id) { var dir = Server.MapPath(“/Images”); var path = Path.Combine(dir, id + “.jpg”); //validate the path for security or use other means to generate the path. return base.File(path, “image/jpeg”); } As a note, this seems to be fairly efficient. I did a test where I requested … Read more

ASP.NET MVC – Set custom IIdentity or IPrincipal

Here’s how I do it. I decided to use IPrincipal instead of IIdentity because it means I don’t have to implement both IIdentity and IPrincipal. Create the interface interface ICustomPrincipal : IPrincipal { int Id { get; set; } string FirstName { get; set; } string LastName { get; set; } } CustomPrincipal public class … Read more

Server.MapPath(“.”), Server.MapPath(“~”), Server.MapPath(@”\”), Server.MapPath(“/”). What is the difference?

Server.MapPath specifies the relative or virtual path to map to a physical directory. Server.MapPath(“.”)1 returns the current physical directory of the file (e.g. aspx) being executed Server.MapPath(“..”) returns the parent directory Server.MapPath(“~”) returns the physical path to the root of the application Server.MapPath(“https://stackoverflow.com/”) returns the physical path to the root of the domain name (is … Read more

Maximum request length exceeded.

If you are using IIS for hosting your application, then the default upload file size is 4MB. To increase it, please use this below section in your web.config – <configuration> <system.web> <httpRuntime maxRequestLength=”1048576″ /> </system.web> </configuration> For IIS7 and above, you also need to add the lines below: <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength=”1073741824″ /> </requestFiltering> … Read more

Can I set an unlimited length for maxJsonLength in web.config?

NOTE: this answer applies only to Web services, if you are returning JSON from a Controller method, make sure you read this SO answer below as well: https://stackoverflow.com/a/7207539/1246870 The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k). You can set the MaxJsonLength property on your web.config: <configuration> <system.web.extensions> <scripting> … Read more

tech