IIS 5.1 + ASP .NET MVC 3 + Image not loaded - asp.net-mvc-3

I am developping a web application by using the ASP .NET MVC 3 framework.
I am using Windows XP Professional on my computer.
I have decided to execute my web application via my IIS 5.1 local server during the development.
First I have installed IIS 5.1.
Then I have created a virtual directory under the default web site for my web application.
Then I have executed the following command line :
aspnet_regiis -i
Then I have added the following extension mapping to my virtual directory :
Executable : C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
Extension : .*
Option "Check file existence" unchecked.
For information here is my RegisterRoutes method written in my Global.asax.cs file :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Accueil", action = "Accueil", id = UrlParameter.Optional } // Default parameters
);
}
When I launch my web application via Visual Studio 2010 in debug mode then I can load one my view with success.
But I noticed that an image was not loaded.
Here is the img tag containing the image :
<img src="../../../Content/images/Valider_064.png" alt="Valider" />
Here is a piece of my web application folder tree :
ActivitesHtml5 [FOLDER] : Root of web application
Content [FOLDER]
images [FOLDER]
Valider_064.png [FILE]
Controller [FOLDER]
ConnexionController.cs [FILE] : Contains the action method to generate my view.
Views [FOLDER]
Connexion [FOLDER]
Connexion [FOLDER]
Connexion.cshtml [FILE] : Razor file of my view.
Does someone know why my image is not correctly loaded ?

How about using url helpers instead of hardcoding your urls:
<img src="#Url.Content("~/Content/images/Valider_064.png")" alt="Valider" />
Also I would totally recommend you to stay away from IIS 5.1 especially if your target deployment server for the application will be IIS 7.0+. Cassini or IIS Express are much better alternatives and are directly integrated into Visual Studio.

Related

How can I deploy a Blazor server-hosted application from Visual Studio 2019

I am using VS2019 Preview.
I have created a "server-hosted" Blazor application using the latest Blazor extension (16.0.19227). This is the variant that contains 3 separate projects...
MyApp.Client
MyApp.Server
MyApp.Shared
I can debug this by making MyApp.Server the active project and all works fine but I'm struggling to publish/deploy this to Azure. I have tried the following...
Right-click on MyApp.Server in Solution-Explorer
Choose "Publish"
Go through the wizard to create a new publish profile
Change the deployment mode to "self-contained"
Hit publish
At this point I get an error during deployment...
CSC(0,0): Error CS0006: Metadata file 'D:\work\Applications\Web\MyApp.Client\bin\Release\netstandard2.0\win-x86\MyApp.Client.dll'
could not be found
This appears to be because the "Target Runtime" in the web-deploy profile is set to win-x86. The client application is actually being built as
"D:\work\Applications\Web\MyApp.Client\bin\Release\netstandard2.0\MyApp.Client.dll"
(without the additional win-x86 subfolder) so the deployment process seems to be making an incorrect assumption about the paths used by the build process. There's no way in the publish dialog to specify a blank/don't care target runtime.
Is there a workaround for this or perhaps I am using the wrong approach for deployment?
There is some official documentation but it's not very helpful.
Update It seems that the deployment is using the output path of the Client project and then just appending netstandard2.0{Target Runtime} to it so changing the output path in the Client project is not enough to work around the issue.
Update 2 Removing the RuntimeIdentifier tag in the publish profile by editing the xml simply results in deploy-time error stating that an empty RuntimeIdentifier is incompatible with a self-contained deployment. Unfortunately the self-contained deployment is necessary because Azure does not yet host .net core 3 directly.
because Azure does not yet host .net core 3 directly.
But it does.
In the Azure Portal, go to your WebApp after deployment (or create one beforehand).
Go to Extensions and click Add [+] and select ASP.NET Core 3 (x86 for the free hosting).
Also go to Settings, General and enable WebSockets, they're Off by default.
Temporary:
Note that Preview-6 is not available as an extension, so either use Preview-5 or deploy as self-contained.
Couldnt put a picture in the comment, so I thought i'd show it here. This is my current publish wizard.
Just did it with a brand new project via new project -> Asp.net core web application -> blazor (Asp.net core hosted) built and published fine to azure app service fine.
My answer is:
Configure the publish profile to "Self-contain" deployment mode.
Edit all .csproj files to change <TargetFramework>...</TargetFramework> node name to <TargetFrameworks>...</TargetFrameworks>. (see also: https://stackoverflow.com/a/42855070 )
Fix the web root folder path string at runtime in Startup class like below.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using System.IO;
using System.Linq;
namespace BlazorHostedOnAzure.Server
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddNewtonsoftJson();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
// ---- APPEND PART.1 BEGIN ----
var clientBlazorWebRootPath = default(string);
// ---- APPEND PART.1 END ----
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBlazorDebugging();
}
// ---- APPEND PART.2 BEGIN ----
else
{
if (env.WebRootPath != null)
{
var pathOfIndex = Path.Combine(env.WebRootPath, "index.html");
var pathOfContent = Path.Combine(env.WebRootPath, "_content");
if (!File.Exists(pathOfIndex) && Directory.Exists(pathOfContent))
{
clientBlazorWebRootPath = Directory.GetDirectories(pathOfContent).FirstOrDefault();
if (clientBlazorWebRootPath != null)
{
env.WebRootPath = clientBlazorWebRootPath;
}
}
}
}
// ---- APPEND PART.2 END ----
app.UseClientSideBlazorFiles<Client.Startup>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
});
// ---- APPEND PART.3 BEGIN ----
if (clientBlazorWebRootPath != null)
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(clientBlazorWebRootPath)
});
}
// ---- APPEND PART.3 BEGIN ----
}
}
}
I published my sample code and README on the GitHub my repository.
https://github.com/sample-by-jsakamoto/BlazorHostedV3Preview6OnAzureWebApp#how-to-configure-client-side-blazor-v300-preview-6-that-is-hosted-on-an-aspnet-core-server-to-deploy-it-to-azure-at-13-jul-2019

ASP.NET MVC add/remove IIS app name/alias from URL dynamically

Because of the IIS 6.1 settings, every app that's being deployed has an alias and that has an impact on the URL. In Visual Studio's development server, the URL looks like this:
http://localhost:27019/controller/action
But after being deployed to IIS:
http://servername/appname/controller/action
as you can see there is an appname added to the URL. All the Ajax calls become incorrect after deployment. I have to create an isIIS variable and manually assign a value to it in order to make it work:
var isIIS = true; // set to false if runs locally;
window.appAlias = (isIIS) ? '/'+window.location.href.split('/')[3] : '';
And in my Ajax call:
$.post( window.appAlias + webUrl, {} , callback );
same thing with GET calls, I have to prepend the window.appAlias. Is there a way to dynamically detect whether the server is IIS or Visual Studio Development Server? I understand the #Uri.Content("~/controller/action") but I am not writing my JavaScript on the Razor view.
I am using Visual Studio 2012, target framework .NET 4.5, MVC 4 and jQuery 1.9.2 for development. The IIS application pool has .NET 4.0.
Edit
Here is my temporary solution: to add global values in _Layout.cshtml:
Object.assign({
action1: '#Url.Content("~/controller/action1")',
action2: '#Url.Content("~/controller/action2")'
}, window);

How to set start page in dotnet core web api?

I try to build a web application with dotnet core web api,but i do not know how to set index.html as start page which can be done with dotnet framework web api easily. And i tried to use app.UseDefaultFiles();app.UseStaticFiles(); to solve this problem, however, it did not work.
In Properties/launchSettings.json you can define the launchUrl
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "<your relative URL here>",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
Step 1
app.UseDefaultFiles();
app.UseStaticFiles();
Step 2
Create a folder called "wwwroot". put a file called index.html
Step 3 (optional)
If you are the using the auto generated template, you can remove make the launchUrl blank like this
"launchUrl": "",
Otherwise, you will have to manually keep going to the landing page every time during localhost running.
This is the correct way. But always use UseDefaultFiles() before UseStaticFiles
Otherwise it won't work.
For reference: Core fundamentals of Static Files
If you are using a static file as the default page, the following code can help you.
app.UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new
List<string> { "index.html" } });
If you are using the MVC view, just add the routing role.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
For Asp.Net Core 2.0/2.1/2.2 just right click on Project → Properties → Debug
and next to Launch Browser checkbox set path to the startup page you want.
Your index.html file must be in the wwwroot folder
wwwroot / index.html
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files
You can set any file in any folder under the wwwroot as defaut file by using options.DefaultFileNames.Add in startup.cs .
For example to use myfile.html in wwwroot/folder1/folder2/ myfile.html, you will add this in Startup.cs
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("folder1/folder2/ myfile.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();
But some time it may not work. For example
I created project File menu > New > Project , then selected .NET Core > ASP.NET Core Web Application and selected Web Api as project template.
F5 always open page api/values, even though I added index.html in wwwroot folder and added following in startup.cs
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mypage.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();
Then I opened project properties page and deleted the value in Debug/Launch browser box (which was set to api/values)
Now setting of startup page is working and mypage.html is startup page. Note that this page should be in wwwroot folder as you have opted to use static files.
For dotnet core web api 3.1, on launchSettings.json file set "launchUrl": "swagger/index.html",
For Asp.Net Core 2.2 right click on Project → Properties → Debug and next to Launch Browser checkbox set path to the startup page you want.
Project VS
If Index.html is in project root, it will be send by default.

MVC Site versus Virtual Application Routing

We use TFS to deploy our applications to multiple environments (Dev, QA, Prod). Simple enough, our Dev and QA environments have URLS like dev.domain/APPLICATION and qa.domain/APPLICATION. So we have a single site with each application as a virtual application.
However in production, they want each application to be its own site, such as APPLICATION.domain.com... Grrr! In Visual Studio, the application's properties is configured to be in a "Virtual Path". I"m not sure how I should go about this issue. The appliation contains code such as: <a href='/APPLICATION/File/Download?id=<#= PkFileId #>'><#= Name #></a> which causes problems in production since its not in a virtual application.
I could make a site called application.domain.com with an empty directory. Then add a Virtual Application, but then I would have to put a redirect in the root of the site to go to the virtual application. Or perhaps I can somehow configure the application? Not sure what my options are... Any suggestions are appreciated!
The appliation contains code such as:
<a href='/APPLICATION/File/Download?id=<#= PkFileId #>'><#= Name #></a>
ASP.NET MVC applications should not contain code like that (a code in which urls are hardcoded). In ASP.NET MVC applications you should always use HTML and Url helpers:
#Html.ActionLink(
Model.Name,
"Download",
"File",
new { id = Model.PkFileId },
null
)
This way it is certain that no matter how your routes are configured or under which virtual directory your application is hosted, it should work.
UPDATE:
After your comment it looks like you are using the Telerik Grid. In this case you may try something along the lines to generate proper anchors:
columns
.Bound(x => x.PkFileId)
.ClientTemplate(
Html.ActionLink(
"<#= Name #>",
"Download",
"File",
new { id = "<#= PkFileId #>" },
null
).ToString()
)
.Title("");

Deploying Asp.Net MVC 2 /C# 4.0 application on IIS 6

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

Resources