Null reference on MVC 2 Server - asp.net-mvc

I'm writing a MVC 2.0 app with VS2010. On my Windows 7 Ultimate 64bit machine it runs fine. On my laptop (Windows 7 Home Premium, 32bit) it is getting a null reference on Server when I call MapPath.
public ActionResult Index()
{
ContentModel content = new ContentModel();
content.Content = ContentInterface.GetHtmlContent(Server.MapPath("~"), "Home");
content.Ads = ContentInterface.GetPartialAds(Server.MapPath("~"), AdCount);
content.Testimonials = ContentInterface.GetTestimonials();
return View(content);
}
I have installed MVC 2 via Webinstaller, I reregistered .Net 4 with IIS. I've confirmed IIS 6 WMI compatibility mode.
Any ideas?

Figured it out: permissions. I granted Full Control to IUSR and it works now.

Related

Configure Autofac to work with ASP.NET MVC and ASP.NET Web Api for an existing application

We have an existing application which has been configured to use AutoFac with ASP.Net MVC:
1) All the controllers, action info and routings have been registered manually using AutoFac
2) Controllers are resolved with an implementation of IControllerFactory's (AutoFacControllerFactory) CreateController() method
3) I have added a new API controller to the existing application
4) Web API routings have been added before any traditional ASP.Net routings as follows:
GlobalConfiguration.Configuration.Routes.MapHttpRoute("GetNetworkFeatures",
"secure/banking/administration/GetNetworkFeatures/Get",
new { controller = "GetNetworkFeatures" });
5) New API controllers have been registered using AutoFac as well before containerBuilder.Build() si called as follows:
foreach (var module in modules)
{
builder.RegisterApiControllers(module);
}
container = containerBuilder.Build();
GetNetworkFeaturesController is loaded in one of the above modules
6) Both dependency resolvers have been registered as follows:
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
7) .Net version is 4.5.2, we are using ASP.Net MVC version 3, AutoFac version is 2.6.3.862, AutoFac.Integration.MVC version is 2.6.3.862, AutoFac.Integration.WebApi version is
2.6.3.863, and Newtonsoft.Json version is 11.0.0.0, IIS server version is 6.1 in Windows Server 2008
8) The target is to make Autofac, Asp.net MVC routing and Web API routing coexist in the same application pool, when I try web API endpoint
http://localhost:7070/secure/banking/administration/GetNetworkFeatures/Get, it still goes to AutoFacControllerFactory's CreateController() method, instead of routing to Get() method of Web API controller GetNetworkFeaturesController
9) I think this may be related to , so I have changed it to true, but the problem still persists. Basically it looks like
configured Web API routing is not respected, although it has no compilation and build errors, if I removed the following default route, it starts to throw HTTP 403 error:
RouteTable.Routes.MapRoute("Default", "{*url}", new { controller = "Unspecified", action = "Unspecified" });
10) The following threads have been referenced:
https://stackoverflow.com/questions/11484904/is-it-possible-to-configure-autofac-to-work-with-asp-net-mvc-and-asp-net-web-api
https://stackoverflow.com/questions/37069666/autofac-with-web-api-controller
https://stackoverflow.com/questions/44986001/web-api-route-values-is-empty-on-action-executes-filter
https://stackoverflow.com/questions/15556035/all-asp-net-web-api-controllers-return-404
https://www.aspforums.net/Threads/218940/Solved-URL-Routing-not-working-with-Web-API-in-IIS-server-and-ASPNet-MVC/
I have fixed up the issue. The reason is we are using a reverse proxy to do the authentication, which is configured to route any authenticated requests of "~/secure/banking/api/XXX" to the real endpoint "api/xxx" in IIS server. If I get rid of the "secure/banking" in the following route template, Web API routing will be respected immediately:
GlobalConfiguration.Configuration.Routes.MapHttpRoute("GetNetworkFeatures",
"secure/banking/administration/GetNetworkFeatures/Get",
new { controller = "GetNetworkFeatures" });
Cheers
William Feng

File download from azure services hosted application get stuck for IE 11

We noticed that file download get stuck after some time in IE 11 client browser if downloaded from ASP.NET MVC application deployed to Azure service. The file download starts normally in IE 11. For several minutes the downloaded file size get increased. Then the yet downloaded file size get stuck with no more increases. If we continue to wait even more for around 1h, then the IE shows 'download was interrupted' error.
Azure instances have IIS 8.5 on board with app pool in default integrated pipeline mode. Application is ASP.NET MVC 5, targeted .NET 4.5.2.
There are no problems with download from Azure for Chrome browser.
There are no problems with download from local IIS express for both IE 11 and Chrome browsers.
There are no problems with download from local IIS 7.5 for both IE 11 and Chrome browsers.
So it looks like the only problem pair is Azure hosted IIS 8.5 + IE 11.
Application use the following code to stream file to client:
private const int StreamBufferSize = 1024*128; // 128KB
public static async Task StreamData(string fileName, Func<Stream, Task> streamFiller, HttpResponseBase response)
{
response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", fileName));
response.ContentType = MimeMapping.GetMimeMapping(fileName);
response.BufferOutput = false;
using (Stream outputStream = new BufferedStream(response.OutputStream, StreamBufferSize))
{
await streamFiller(outputStream);
}
}
Where 'streamFiller()' is externally passed Func that writes data to the stream.
Please note that file is not so large, around 20Mb, but server do not send it at once. Instead server streams file with buffered chunks (see code above). Time between each chunk get streamed (buffer flashed) may be as long as several minutes.
By looking into Azure IIS I found that the client request looks like the following:
during normal download phase: State: ExecureRequestHandler, Module Name: ManagedPipelineHandler
since the download get stuck: State: SendResponse, Module Name: RemoveUnnecessaryHeadersModule.
To be clear what is RemoveUnnecessaryHeadersModule: we do the 'Server' header removing as following:
public class RemoveUnnecessaryHeadersModule : IHttpModule
{
public void Init(HttpApplication context)
{
// This only works if running in IIS7+ Integrated Pipeline mode
if (!HttpRuntime.UsingIntegratedPipeline) return;
context.PreSendRequestHeaders += (sender, e) =>
{
var app = sender as HttpApplication;
if (app != null && app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
};
}
}

How to perform a request to a REST API in ASP.net 5.0 (MVC6)

I am writing an ASP.Net 5, MVC 6 application (also referred to as 'ASP.net vNext') with Visual Studio 2015 RC.
How do I perform a simple GET request to a REST API? In .net 4.5 I would have used HttpClient but that no longer seems to be available.
I have tried adding both the 'System.Net.Http' and 'Microsoft.Net.Http' packages as advised by Visual Studio, however I still get "The type or namespace name 'HttpClient' could not be found" which leads me to believe that HttpClient is not the right way to do this in ASP.net 5?
Can anyone advise on the correct way to make HTTP GET requests in ASP.net 5?
Update: My question is not a duplicate of 'HttpClient in ASP.NET 5.0 not found?' bercause the answer given is out of date and not applicable to the latest version of ASP.net 5.0
Here is a solution for you, I just tried it out on the ASP.Net 5 Web site project template. Add the following method to HomeController
static async Task<string> DownloadPageAsync()
{
string page = "http://en.wikipedia.org/";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
return result.Substring(0, 50);
}
}
Then in the HomeControllers Index method
string test = DownloadPageAsync().Result;
And in project.json I added the following reference at dependencies
"Microsoft.Net.Http": "2.2.22"
I found an answer which was in part from a post called '
HttpClient in ASP.NET 5.0 not found?', but there were some missing gaps because the technology has moved on a bit now. I have blogged the full solution here: http://blogs.msdn.com/b/martinkearn/archive/2015/06/17/using-httpclient-with-asp-net-5-0.aspx

How to print from MVC3 controller from server

Code below is used to print from ASP .NET MVC3 application to Samsung ML-331x Series printer connected to IP address in LAN and shared in server as Samsung ML-331x Series
Nothing is printed. Execution stops at doc.Print() line.
Every controller call adds new unfinished job:
Those jobs are never finished, only iisreset clears them.
Server is Windows 2003 + IIS
It worked in MVC2 .NET 3.5 application. ForteSSL VPN was installed in server and application was upgraded to
MVC3 and .NET 4.
(After that printing was not checked immediately, so I'm not sure is this related to those changes).
User NETWORK SERVICE with all permissions is added to printer users but problem persists.
Running application in development computer by pressing F5 in visual studio with Web Developer server and calling with controller to print to PDF Creator works OK.
How to print from controller in server ?
public ActionResult PrintTest()
{
var doc = new PrintDocument();
doc.PrinterSettings.PrinterName = "Samsung ML-331x Series";
doc.PrintPage += new PrintPageEventHandler(TestProvideContent);
doc.Print();
return new ContentResult()
{
Content = "Printed"
};
}
public void TestProvideContent(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString("Test",
new Font("Arial", 12),
Brushes.Black,
e.MarginBounds.Left,
e.MarginBounds.Top);
}
Update
Application runs at full trust Level.
Application log in event viewer does not have any entries about this.
Using Programmatically "hello world" default SERVER-side printer in ASP.NET MVC I tried to use printer name with server name as \\SERVER\Samsung ML-331x Series but problem persists.

Routing error with IIS 7 versus IIS Express generating HTTP 404 errors

I am using MVC 3 with Visual Studio 2010 and C# 4.0. My application works correctly under IIS Express from Visual studion and when deployed to a remote production IIS 7.5 server.
When I switch to using the full IIS 7.5 server on my development system I have suddenly started to get HTTP 404 errors for the actions in two of my controllers. The other controllers function correctly. This is either running the application from Visual Studio or directly from IIS.
I can see no configuration differences.
One of the controllers that is exhibiting this behaviour is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Mbrrace.ApplicationServices.Validation;
namespace Mbrrace.WebUI.Areas.Validation.Controllers
{
public class ValidationController : Controller
{
//
// GET: /Validation/Validation/
[HttpGet]
public JsonResult PostcodeCheck([Bind(Prefix = "perinatalView")]AddressViewModel model)
{
// postcode has already been checked for correct format
// now look it up to see if it exists
if (PostcodeChecks.CheckPostcodeExists(ConfigurationManager.ConnectionStrings["CommonCodeEntities"].ConnectionString, model.Postcode))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("This postcode was not found in the database", JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult PostcodeExtendedCheck(String Postcode)
{
// check if it exists or of it's sector exists (all but last two characters
string message = PostcodeChecks.PostcodeExtendedCheck(ConfigurationManager.ConnectionStrings["MbrraceCommonCodeEntities"].ConnectionString,
Postcode, Postcode.Substring(0, Postcode.Length - 2));
string success = (message.Length == 0) ? "OK" : "NO";
var result = new { Success = success, Message = message };
return Json(result, JsonRequestBehavior.AllowGet);
}
public class AddressViewModel
{
public string Postcode { get; set; }
}
}
}
This behaves as expected in IIS Express and a deployed to IIS. It throws a 404 error when IIS is connected to the project for debugging.
Can anyone please shed any light on why the 404 errors are being generated?
The first thing I am thinking is about IIS configuration.
Is there an Application Pool for the site configured in Integrated Mode?
you can also try to add in the global.asax an Application_OnError and check in there the server.GetLastError
another option should be to use Glimpse to see what routing problem you could have (if it is a routing problem)
after this if you don't find the problem post some more detail of IIS configuration

Resources