i developed a website(MVC 5) and upload it on a iis7 on a web server.
i handle errors on method
protected void Application_Error(){}
on the Global.asax.
yesterday i did some tests on it and i saw when i enter this url
http://www.xxxx.com/.
i can get invalid rout on Application_Error method but when i entered that URL with 3dotes or more like this URL
http://www.xxxx.com/...
i saw a webpage with this content and Application_Error not works because i have no default page or view with this content on my project.
The page cannot be displayed because an internal server error has occurred.
i did some test on another website on the internet and i saw some of theme has the same issue and i think i should do some config on my IIS.
if yes , what config(s) i should set on my IIS and if no what i can do with my project until i can handle it?
You can try this configuration in the web.config file:
<customErrors mode="On|Off|RemoteOnly" defaultRedirect="URL">
<error statusCode="404" redirect="URL" />
<error statusCode="402" redirect="URL" />
<error statusCode="500" redirect="URL" />
</customErrors>
Example:
I created a ErrorHandlerController with the following ActionResult's:
//This action return a view that show the http error you specified.
public ActionResult Error()
{
return View();
}
//This action return a view that show the 404 http error captured.
public ActionResult NotFoud()
{
return View();
}
//This action return a view that show the 402 http error captured.
public ActionResult Unauthorized()
{
return View();
}
In the web.config file of my project:
<customErrors mode="RemoteOnly" defaultRedirect="~/ErrorHandler/Error">
<error statusCode="404" redirect="~/ErrorHandler/NotFoud" />
<error statusCode="402" redirect="~/ErrorHandler/Unauthorized" />
<error statusCode="500" redirect="~/ErrorHandler/Error" />
</customErrors>
NOTE: Change the URL with your CustomURL desired.
Help: https://msdn.microsoft.com/en-us/library/h0hfz6fc%28v=vs.85%29.aspx
Related
We are having problems with partial views after migrating to .net 5. The main page will optionally render a custom partial view to allow per-customer customizations. After migrating we are unable to render these partial views. the error message is:
InvalidOperationException: The partial view ~/Resources/Customer/Views/File.cshtml was not found. The following locations were searched: ~/Resources/Customer/Views/File.cshtml
We know the path is valid because if we rename the file the page renders (without customizations). If we debug in visual studio the page renders as expected but in a deployed IIS server it fails. We suspect there is a permissions issue but we have been unable to find it. So far we haven't been able to find anything in google searches or SO
Here is a snippet where we handle the custom file:
// load file path from config
string url = configuration.OrderPageSetting["OrderInfoViewRenderFile"];
bool exists = false;
// determine the path
if (!string.IsNullOrWhiteSpace(url))
{
string _url = url;
if (_url.StartsWith("~/")) _url = _url.Substring(2);
else if (_url.StartsWith("/")) _url = _url.Substring(1);
exists = System.IO.File.Exists(System.IO.Path.Combine(Resource.SystemDirectory, _url));
}
// test for and render custom view
if (exists)
{
var data = new ViewDataDictionary<object>(new EmptyModelMetadataProvider(), new ModelStateDictionary());
data.Add("Order", order);
data.Add("Config", configuration);
await Html.RenderPartialAsync(url, data);
}
else
{
... default rendering ...
}
The application is hosted in a virtual directory with a dedicated application pool. This problem occurs without a web.config at the site level. On the same server, the prior .net framework version of the application works correctly.
here is the applications web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\myapp.dll" stdoutLogEnabled="false" hostingModel="InProcess" stdoutLogFile=".\logs\stdout">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
A co-worker found the solution the problem, the clue was in https://weblog.west-wind.com/posts/2019/Sep/30/Serving-ASPNET-Core-Web-Content-from-External-Folders
There were 2 changes required:
Add package: Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
called extension to support runtime complication on the controllers/views:
services.AddControllersWithViews().AddRazorRuntimeCompilation(opt =>
{
opt.FileProviders.Add(
new PhysicalFileProvider(System.IO.Path.Combine(Environment.ContentRootPath, ""))
);
})
if you want to change where the dynamic compilation is supported, simply change the "" to the path where it is permitted.
I've project in ASP NET Core 3.1 with Windows Authentication. I would like to use custom error code page.
This a basic example.
In HomeController :
[Route("/Error/401")]
public IActionResult StatusCode401()
{
HttpContext.Response.StatusCode = 401;
return View("ErrorUnauthorized");
}
But when I call StatusCode401 method, Windows prompt dialog (login, password) appears, if I cancel it, I see my custom view.
If I disable Windows Authentication, it's works fine.
How disable Windows prompt dialog when I use Windows Authentication ?
Thanks
You can open the web.config,
And then find the statusCode 401, change the responseModel from ExecuteURL to File
<system.webServer>
<httpErrors errorMode="Custom" >
<error statusCode="403" subStatusCode="0" prefixLanguageFilePath="" path="***" responseMode="ExecuteURL" />
<error statusCode="401" subStatusCode="2" prefixLanguageFilePath="" path="***" responseMode="File" />
....
</httpErrors>
</system.webServer>
I’m trying to remove the response Server header from an Azure Web App ( with an ASP Net core application )
After many tries of changing the web.config and removing the header in app code using a middleware, Microsoft doesn’t give up and set the response header to Server: Microsoft-IIS/10.0 :)
The problem appears only when I’m trying to access the server on http (not https). Response code from the server is 301, and this is the only response that has the Server header.
Checking the logs I was not able to find any request to http://, and perhaps this is why I’m not able to remove header, because the request is not process in my application code.
A solution that I’m thinking is to disable the azure HTTPS only and do the redirect to https in my code (I tested and is working - server header is removed)
Is there another workaround without disabling the HTTPS only option?
Here is what I tried
Startup.cs
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
context.Response.Headers.Add("server", string.Empty)
}
app.UseHttpsRedirection();
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime enableVersionHeader="false" />
<!-- Removes ASP.NET version header. -->
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="Server" />
<remove name="X-Powered-By" />
</customHeaders>
<redirectHeaders>
<clear />
</redirectHeaders>
</httpProtocol>
<security>
<requestFiltering removeServerHeader="true" />
<!-- Removes Server header in IIS10 or later and also in Azure Web Apps -->
</security>
<rewrite>
<outboundRules>
<rule name="Change Server Header"> <!-- if you're not removing it completely -->
<match serverVariable="RESPONSE_Server" pattern=".+" />
<action type="Rewrite" value="Unknown" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
UPDATE
When the URL of http:// is requested, IIS will process it, this time without code. So we can't control it by the code, we can only set it on the server, such as some scripts or tools. But on Azure, we have no way to directly operate as a physical server, so after exploration, I suggest that Front Door can be used to deal with this problem. Hiding server information through proxy should be a better way.
After my test, the server information is hidden, you can refer to this document . We can see from the picture that there is no 301 redirect request, and no server information in other requests.
PREVIOUS
You need to modify Global.asax.cs and Web.config file in your program.
In Global.asax.cs.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
MvcHandler.DisableMvcResponseHeader = true;
PreSendRequestHeaders += Application_PreSendRequestHeaders;
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
}
And In Web.config.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
</modules>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
Then u can deploy your app. After the above code modification, access to the interface or static resources can see that the server information is modified, of course, it can also be deleted by Remove.
You also can handle special event by http status code.
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
int StatusCode= HttpContext.Current.Response.StatusCode;
// handle like http status code 301
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
If something breaks in my code i was trying to show an custom error page so i have tried the following
1)placing the below in web.config file
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<customErrors mode="On" defaultRedirect= "Error.aspx">
</customErrors>
</system.web>
2)And tried placing the following in Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Server.ClearError();
Response.Redirect("Error.aspx");
}
3) i tried it having in page level like below
ErrorPage="~/Error.aspx"
None of them have worked , The main intention for me to show custom error page is when a value is retrieved from the database it should bind to the screen for the old records we don't have few elements so i thought of showing custom error message ,Please help me /suggest me ( i am using .net framework 4.5)
I'm trying to debug in VS express 2013 with my MVC4 application.
In a view, I've added a nonsense link, such as link, but I don't see the intended View when I click on the link, I see the IIS page.
I did this by creating an ErrorController which is
public class ErrorController : Controller
{
public ActionResult Index()
{
return View();
}
}
My view remains as the default, I didn't update it.
And my webconfig is
<customErrors mode="On" defaultRedirect="~/Error">
</customErrors>
The routes are the default!
The IIS message is
HTTP Error 404.0 - Not Found
If I type in http://localhost:53258/error/ then I see the page, suggesting that the mapping is fine.
What have I done wrong?
Check for this in your web.config, and add it if you don't have it:
<httpErrors errorMode="Custom" existingResponse="PassThrough" />
Try updating your customErrors node to add this:
<error statusCode="404" redirect="~/Error" />
Thus, your custom errors section would look like:
<customErrors mode="On">
<error statusCode="404" redirect="~/Error" />
</customErrors>