I got a problem migrating from VS.Net 2008 / MVC 1 to VS.NET 2010 (+C# 4.0) / MVC 2
The web.config has been updated, the site runs well in Cassini, but my problem now is deploying on IIS 6.
I updated the web site to run using ASP.Net 4,
but whatever URL I try, I always have a 404 error. It's as if the routing was not taken into account (yes, the wildcard mapping has been done).
I do not understand this mess and could not google anything interesting...
Thanks for your suggestions !
Ok I got y answer (thanks to a colleague)
When migrating from ASP.Net 2.0 to ASP.Net4.0,
if you meet the same problem,
then check in Web Service Extension if ASP.Net v4 is Allowed.
In my case, after installing the .Net framework 4, it was prohibited.
Will & Mark : thanks for your help, hope it will helps others.
I think I know what's happening: on IIS6, as well as the wildcard mapping you will need a default document (Default.aspx) that routes folder requests to the MVC handler.
There was one included with the MVC1 project templates, but it has been removed in MVC2.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YourNameSpace._Default" %>
<%-- Please do not delete this file. It is used to ensure that ASP.NET MVC is activated by IIS when a user makes a "/" request to the server. --%>
and Default.aspx.cs:
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace YourNameSpace
{
public partial class _Default : Page
{
public void Page_Load(object sender, System.EventArgs e)
{
// Change the current path so that the Routing handler can correctly interpret
// the request, then restore the original path so that the OutputCache module
// can correctly process the response (if caching is enabled).
string originalPath = Request.Path;
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
HttpContext.Current.RewritePath(originalPath, false);
}
}
}
When you say "It's as if the routing was not taken into account", I suspect that it actually isn't, and this is your problem.
This finally fixed it for me:
I commented earlier, and a wee bit prematurely. My comment to Mark B's post was getting my initial Index view to show up, but then I kept getting the 404 errors whenever I navigated to any other view.
I was also distracted by the green check mark approved solution in this particular forum, but I could not even see the web server extensions folder in IIS 6 on my desktop; therefore, I had no control from that stand point of enabling aspnet 4.0, though I made sure it was installed by performing running the following command line:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i
Now for the actual piece that finally allowed me to navigate to the other views besides just my Home/Index:
In the Global.asax.cs file of your VS 2010 Solution, you will see code as follows in the RegisterRoutes method:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
I simply added ".aspx" after the {action} section of the tag as follows:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}.aspx/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
And ahla wahla Peanut Butter and Jelly sandwiches. :0)
If you want to do it in C#, just add the System.DirectoryServices reference and this piece should do the job nicely.
DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/W3SVC");
w3svc.Invoke("EnableWebServiceExtension", "ASP.NET v4.0.30319");
w3svc.CommitChanges();
HTH
Related
I am trying to display the SSRS report in a .Net Core 3.1 MVC application.
I tried to implement the approach mentioned in
https://alanjuden.com/2016/11/10/mvc-net-core-report-viewer/?unapproved=58532&moderation-hash=321d5350c96d2fcf83baa4c939bbdf53#comment-58532
public class ReportsController : AlanJuden.MvcReportViewer.ReportController
{
protected override ICredentials NetworkCredentials
{
get
{
//Custom Domain authentication (be sure to pull the info from a config file)
return new System.Net.NetworkCredential("username", "password");
//Default domain credentials (windows authentication)
//return System.Net.CredentialCache.DefaultNetworkCredentials;
}
}
protected override string ReportServerUrl
{
get
{
//You don't want to put the full API path here, just the path to the report server's ReportServer directory that it creates (you should be able to access this path from your browser:
return "https://YourReportServerUrl.com/ReportServer/ReportExecution2005.asmx";
}
}
public IActionResult ProcessReport()
{
var model = this.GetReportViewerModel(Request);
model.ReportPath = "reportPath";
return RedirectToAction("ReportViewer", model);
}}
but it is not working with the latest framework.
I am getting following error while running the project - Error screenshot
Any help is appreciated.
Thanks!
The same thing happened to me, in my case I needed to install the same package that tells you to install
Install-Package System.ServiceModel.Http -Version 4.1.0
or in the nuget look for the package System.ServiceModel.Http
I tried different workarounds with latest .NET Core including the one you mentioned from Alan Juden. However the easiest thing that worked for me is to create a plain .NET WebForms site using the Report Viewer control from Microsoft. It was still a lot of code but this is solid because the Report Viewer control has been around for many years.
In my case it is showing SSRS Report from Angular UI, but the same will work with MVC or any other Web UI because you will actually redirect/navigate to another url (WebForms aspx page).
More details here.
We have an existing MVC2 project that we just upgraded to MVC4 following first these steps to get to MVC3, then these steps to get to MVC4.
Output caching had been successfully working for a long time in our MVC2 project, but it does not work after the MVC4 version.
I've added a simple controller to test caching:
public class TestController : Controller
{
[OutputCache(Duration = 600, VaryByParam = "*")]
public ActionResult CacheTest()
{
return Content(DateTime.Now.ToLongTimeString());
}
}
Each time i refresh this page, the time output to the browser changes.
Creating a new MVC3 project in this same solution, then upgrading to MVC4, then copying this same code over works as expected.
So there must be something somewhere in our existing code or configuration that is breaking output caching.
I've also tried stripping out a ton of stuff from the web.config file thinking something there was causing problems - no luck.
Any suggestions on how to fix or debug this?
UPDATE:
Rendering the CacheTest action above in any view will display cached results - i.e. the date does not change on each refresh:
<% Html.RenderAction("CacheTest", "Test"); %>
Why does that work, but the action url from a browser is never cached?
Turns out this was an issue with a third party library - 51Degrees. This was an issue introduced into a recent version of this library. In the process of converting from MVC2 to MVC4 I installed the nuget package which was a few versions later than the previous version I was using.
False alarm - nothing to do with the ASP.NET MVC upgrade or anything ASP.NET related.
I'm running a mixed MVC Application inside a sub folder of a web forms application.
Everything worked great in VS 2010 debug (Cassini) but when I deployed to IIS7.5
I got the following error:
'HttpContext.SetSessionStateBehavior' can only be invoked before
'HttpApplication.AcquireRequestState' event is raised.
It errors on the last line (httpHandler.ProcessRequest(HttpContext.Current);) in the default.aspx file of the MVC application sub folder.
public void Page_Load(object sender, System.EventArgs e)
{
string pathToRewriteTo = Request.Path.ToLowerInvariant().Replace("default.aspx", "Home/Index");
HttpContext.Current.RewritePath(pathToRewriteTo, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}
However if I manually navigate to Home/Index from the MVC root folder I can see my application fine from there.
I've looked up the error being thrown and I only find answers dealing with server transfers and not MVC routes.
I have also already checked my IIS7.5 configuration for the route handling module, Application pool running in integrated mode, etc.
Any help would be appreciated.
We faced a similar issue. There are changes to MVCHttpHandler in MVC2 and above.
You need to change it to use httpContext.Server.TransferRequest.
Try the below snippet:
var httpContext = HttpContext.Current;
httpContext.Server.TransferRequest(Url, true); // change to false to pass query string parameters if you have already processed them
I created a new MVC3 project, hit F5, saw the sample page.
Then I used NuGet to get the Ninject.MVC extension. I modified my global.asax according to the Ninject documentation, How To Setup an MVC3 Application:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional });
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Now when I run the app, I get the yellow screen of death with the following exception:
InvalidOperationException - Sequence contains no elements.
at System.Linq.Enumerable.Single(...)
at Ninject.Web.Mvc.Bootstrapper.Initialize(...)
line 67.
And sure enough, line 67 of that file calls .Single(), thus throwing the exception.
What am I doing wrong?
I have to add to this in the hopes that someone else will resolve the issue more quickly and not want to pull out every strand of hair on their head like I almost did.
I needed to rename everything in my project to match new business terms. I changed namespaces everywhere and I even changed the Assembly Name (right-click project > properties > application tab) so that the generated assembly matches the new naming convention. The assembly rename is what made Ninject very angry!
By renaming the assembly that gets generated a new file with the new name was being created when we compiled. However, the old file with the old name was still in the bin directory! If you have Ninject activating via the added class in App_Start then this activation class will get invoked in BOTH assemblies (old one AND new renamed one). Don't ask me how or why, but it does and it gives you this "already initialized" error.
Not even cleaning solution works because Visual Studio will only remove the binaries that it is generating, which would be the new renamed ones. It leaves the old ones alone just sitting there.
Go delete your bin folder before you try doing anything else! I hope this saves someone else from wasting valuable working hours!
You might notice that after installing the ninject.mvc3 NuGet there is an App_Start subfolder created inside your project containing an NinjectMVC3.cs file. Delete this folder and try again. So here are the steps I followed:
Create a new ASP.NET MVC 3 project using the default template
Bring up the Package Manager Console window (View -> Other Windows -> Package Manager Console)
Type install-package ninject.mvc3 on the command line
Replace the default code in Global.asax with the code in your question
Delete the AppStart subfolder created during the installation of the package
Run the application
Enjoy the beauty of the /Home/Index default page opened in your Google Chrome web browser :-)
I have updated the documentation Wiki linked in your question to show both ways to setup a MVC3 application. I suggest to use the second option which is the prefered way for theNuGetpackage.
Instead of deriving from NinjectHttpApplication it is using the NinjectMVC.cs in the AppStart folder which is created during installation of the package. This is also the location where you create the kernel and where you load your modules or where you define the bindings.
As Alex Ford said:
I have to add to this in the hopes that someone else will resolve the
issue more quickly and not want to pull out every strand of hair on
their head like I almost did.
I had a special version of that problem which could get solved as follows:
Exception Details: System.InvalidOperationException: Sequence contains no elements
This error is caused by the fact that there are 2 projects with
App_Start/NinjectWebCommon.cs
Removing the file eliminates the error.
Note: if you are nu-getting Ninject.Web.Common because you need to
reference Ninject.Web.Common assembly for one of your class library
project, you can safely remove the “App_Start” folder and
“NinjectWebCommon.cs”. It is meant for web/web api projects.
>click here to view the original blog entry<
My solution was that I had set the App_Start folder property, Namespace Provider to True.
I had changed this to False so that Resharper wouldn't highlight the namespace NOT matching the folder structure.
Wanted to add one more cause ...
We installed the Ninject.MVC3 package to multiple projects - only one of which was an actual MVC applicaiton. However, we forgot to remove the App_Start folder.
Removing the App_Start folder from the referenced project resolved the issue.
To tack on to #Chev's answer... this was my ultimate issue as well. If you're deploying to an Azure Website (now named AppSite), you want to click on this box in the publish to remove old files
I have a web app based on MVC3 (no beta or release candidate, RTM/RTW version) that has an action that accepts XML files for processing.
Of course, this seems evil to MVC because of possible attacks, so it doesn't allow it. Well, I try to put either AllowHtml on the model object as such:
public class XMLModel
{
[AllowHtml]
public string msg { get; set; }
}
Or I set ValidateInput to false on my action method such as this:
[ValidateInput(false)]
public ActionResult AddCDR(XMLModel model)
{
}
The reason for having a "strongly" typed model in the first place was that I originally tried to have a string value named "msg" as the action method parameter, but that always came back empty.
Now, when someone posts to this form, either on the same machine or from a networked computer, the msg field is always blank.
I have verified with WireShark that the data is actually in the request.
Now, one interesting thing. This should not be necessary with MVC 3. Yet it makes a slight difference.
If I add this to my web config:
<httpRuntime requestValidationMode="2.0" />
It works for requests originating from the local computer, but it does NOT work from another system.
I think the AllowHtml version seems elegant - if only it worked.
I have also found out about a bug in RC2 - again, this should not affect me, but I tried to add the following in Application_Start() anyway:
ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();
As expected, it makes no real difference.
Everything works as expected on my development computer (Win7x64, VS2010), but on the target system (Win2008R2x64, IIS7.5) the above problems are giving me a hard time.
Very important point to note: If I post to the action with no angle brackets, I get the form data as expected. As soon as the angle brackets show up, though, either my action isn't called at all, or it doesn't find the form data, neither in action method parameters or in for instance Request.Params["msg"] where it should be.
Any ideas to allow the XML through?
UPDATE
I've tried to work my way around this while waiting for anyone to come up with an answer here. I have not been able to solve it yet, but I have checked a few additional details;
First, I verified that the ASP.NET MVC 3 version installed on both my development computer and on the web server is the same; v3.0.20105.0 (according to Add/Remove programs).
The web application was actually created with the MVC3 beta, then converted to RC1 and RC2 as they came out, and finally to the RTM version. This meant I had to modify some code because of the ViewBag change. However, since I didn't know exactly what else had changed, I created a brand new MVC3 application with the RTM version, created a controller by the same name, with the same action method, taking a model object similar to the currently used one, renamed the old web app directory and put this new one in place. Exactly the same thing happens - i.e. the parameter with the AllowHtml attribute comes through with all content when the request is made from the local machine, but if it comes from a remote machine, then the HTML (XML actually) is stripped out.
There is no exception. I've installed Elmah and verified this - no exception occurs, my action method is apparently just called with anything looking like XML stripped out from the parameters to the method.
Needless to say, this is driving me crazy. I had some advice yesterday to look at the source code of MVC3, but unfortunately that doesn't really help me, as I can't see anything obviously wrong there, and I can't debug code on the server in question.
Any insights still highly desired, thanks! :)
I cannot reproduce this.
Model:
using System.Web.Mvc;
namespace MvcApplication3.Models {
public class XmlModel {
[AllowHtml]
public string msg { get; set; }
}
}
Controller:
using System.Web.Mvc;
using MvcApplication3.Models;
namespace MvcApplication3.Controllers {
public class HomeController : Controller {
public ActionResult Index() {
return View();
}
[HttpPost]
public ActionResult Index(XmlModel model) {
return View();
}
}
}
View:
#model MvcApplication3.Models.XmlModel
#using (Html.BeginForm()) {
<div class="editor-label">
#Html.LabelFor(model => model.msg)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.msg)
#Html.ValidationMessageFor(model => model.msg)
</div>
}
These were added to a default empty MVC 3 project. Everything posts fine. When I remove [AllowHtml], it generates the appropriate error message.
I am answering this myself because this was an obscure situation, and MVC3 was not the problem.
The system that POSTed data to my application was doing so with malformed data. In addition to that, I was told that they were also POSTing to an older MVC2 application that worked just fine - this was wrong, it turned out they were GETting in that case, and GET they happen to do correctly.
If anything, fairly thorough testing has confirmed that the AllowHtml attribute actually works very well. Never trust your input, tho. :)