How do i read from app.config and web.config.
app.config reading is as follows .how do i read from web.config
using System.Configuration;
string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
also why do we store in these config files?
And How do i read from a user defined tag <display> in app.config below ??
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<display>
<add key="countoffiles" value="7" />
<add key="logfilelocation" value="abc.txt" />
</display>
</configuration>
what is the difference between values stored in app.config and web.config?
How do i decide where to keep certain data?
i got this error when i added <display> tag to the web.config in MVC application.Any clues on why??
Web.Config is used for applications hosted at IIS (Websites, Webservices)
App.Config is used for any other .NET applications like (WinForms, WPF, Windows Services)
To read from custom section I would go that way:
NameValueCollection displaySection = (NameValueCollection)ConfigurationManager.GetSection("display");
string countoffiles = displaySection ["countoffiles"];
string logfilelocation = displaySection ["logfilelocation"];
In regards to configuring custom sections, please check that article:
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx
Related
I am trying to upload a large file to my ASP.net core/ASP.net mvc site, but keep on encountering HTTP 413 - request entity too large. Even when I try to update web.config, other things still break.
Does anyone have a cheat sheet for dealing with this?
I created an asp.net mvc application and tried to test it.
Often we only pay attention to the uploadReadAheadSize setting, but tests have proved that this cannot completely solve the problem, and there are other configurations that need to be configured. (Added based on Jack's answer)
In addition to setting the uploadReadAheadSize value larger, there are also maxAllowedContentLength and maxRequestLength. You need to modify all these three values, otherwise the 413 or Maximum request length exceeded error will still be displayed.
In my test results, the application can upload any type of file within 1GB.
This works for me. Set it in your web.config under the configuration section:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="999999999" />
</requestFiltering>
</security>
</system.webServer>
Here is my cheat sheet:
The max file size limit coming through from IIS is specified through the UploadReadAhaead parameter, which can be specified in web.config as so. In this case, the maximum is set to 1000485760 bytes
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed"></httpErrors>
<serverRuntime uploadReadAheadSize="1000485760" />
<httpErrors errorMode="Detailed" />
<asp scriptErrorSentToBrowser="true"/>
</system.webServer>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
</system.web>
</configuration>
This is grand, as long as this specifier actually works. You might need a different solution, say, if you are hosting locally with something other than IIS (like kestrel, or even IIS express.)
Sometimes this configuration section is locked as well, in which case it can be unlocked using the following command (run cmd as admin):
%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/serverRuntime
This is also something to consider when setting up prod. In some cases, your configuration within web.config within your code for the uploadReadAheadSize can conflict with whatever is specified in your prod instance. For me, I ended up getting rid of my configuration within source control, and instead, set the uploadReadAhead value for prod during environment set up. I did this by running the command (in cmd as admin):
appcmd set config "https://example.com" /section:system.webserver/serverruntime /uploadreadaheadsize:500048576 /commit:apphost
appcmd set config "http://example.com" /section:system.webserver/serverruntime /uploadreadaheadsize:500048576 /commit:apphost
I also set uploadReadAheadSize within C:\inetpub\wwwroot\web.config on the prod server as well, so it looks something like:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<serverRuntime uploadReadAheadSize="500485760" />
<!--If this line breaks, unlock the config by opening cmd as admin and running %windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/serverRuntime-->
</system.webServer>
</configuration>
This can also be set as per this screenshot:
[![enter image description here][1]][1]
Now that you've set this up, it's still entirely possible that your application breaks, giving you a 413 because even though IIS may be set up correctly, there are also upload limits within the .net core ecosystem which can throw an HTTP 414 error when handling large files. This is something I found out [here][2]
The TLDR of this is that you want to have the following code within your startup.cs -> configureServices()
services.Configure<IISServerOptions>(options => {
options.MaxRequestBodySize = int.MaxValue;
});
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue;
x.BufferBodyLengthLimit = int.MaxValue;
x.MultipartBoundaryLengthLimit = int.MaxValue;
});
Note that there is code in there for if you are hosting for kestrel rather than IIS, also
[1]: https://i.stack.imgur.com/yLHQQ.png
[2]: https://github.com/dotnet/aspnetcore/issues/20369#issuecomment-607057822
We have a multi-tenanted MVC app, meaning that exactly the same app is published to multiple IIS virtual directories / applications, and then the app its self works out who it is, and skins its self (css) accordingly.
This is all very well, but anything logged by ELMAH in our elmah database gets logged under the same applicationName, as this is pulled out of Web.Config elmah section below where everything would be logged as "MyappName" :
<configuration>
[...]
<elmah>
<security allowRemoteAccess="false" />
<errorLog
type="Elmah.SqlErrorLog, Elmah"
connectionStringName="elmah"
applicationName="MyappName" />
</elmah>
</configuration>
The question is therefore how to override the applicationName setting from web.config with something specific so we can distinguish errors for a given tenant web site.
As this is configurable within the web.config, ELMAH are already providing you with a way to specify the application name when the application is deployed to different locations - it's just a case of making use of it.
This would generally be something that you would manipulate as part of your deployment steps. If you are doing it manually then it's going to be a pain, but it could be easily manipulated by using a web.config transform.
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<elmah>
<errorLog applicationName="MyappName" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</elmah>
</configuration>
I wonder if the following might work, if you put the following into your Global.asax:
var service = ServiceCenter.Current;
ServiceCenter.Current = context =>
{
var connectionString = "YOUR CONNECTION STRING";
var container = new ServiceContainer(service(context));
var log = new SqlErrorLog(connectionString) { ApplicationName = "APP NAME HERE" };
container.AddService(typeof(ErrorLog), log);
return container;
};
I know that it's possible to setup Serilog sinks in app.config file (AppSettings section) and it's pretty simple with scalar types, but how to be with complex ones (IFormatProvider etc.). Does anybody know how to deal with that and is it possible at all?
I'm trying to simulate this example
ILogger logger = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.WriteTo.Sink(new RollingFileSink(
#"C:\logs",
new JsonFormatter(renderMessage: true))
.CreateLogger();
but using app.config only.
You can use something like JsonRollingFile for this.
<configuration>
<appSettings>
<add key="serilog:using:Json" value="Serilog.Sinks.Json" />
<add key="serilog:write-to:JsonRollingFile.pathFormat" value="C:\Logs\myapp-{Date}.jsnl" />
</appSettings>
</configuration>
Wondering if anyone has seen this behavior before. My instance of Sitecore 6.6 appends the port number to all the URLs it generates for my site. So for example, a link to the home page should be "https://example.org", but instead it's generated as "https://example.org:443". Everything functions fine with the port numbers, but it's muddling some stuff we're trying to do with SEO and canonicalization. Does anyone know if there's a setting or setup to not produce the port numbers? (I'm sure I could rewrite the URLs by catching them at the appropriate point in the pipeline, but I'm hoping for a simpler way before I jump to that.)
The Sitecore LinkManager is indeed not so clever. We also experienced this issue with a mix of proxy servers and load balancers. To remove the ports, we have created a custom LinkProvider which removes the port if needed (untested code sample):
public class LinkProvider : Sitecore.Links.LinkProvider
{
public override string GetItemUrl(Item item, UrlOptions options)
{
var url = base.GetItemUrl(item, options);
if (url.StartsWith("https://"))
{
url = url.Replace(":443", string.Empty);
}
return url;
}
}
And configure the new LinkProvider:
<configuration xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<linkManager defaultProvider="sitecore">
<providers>
<add name="sitecore" set:type="Website.LinkProvider, Website" />
</providers>
</linkManager>
</sitecore>
</configuration>
This is caused by having the 'scheme' property in the configuration/sitecore/sites/site element of the web.config (or patched config) being set to 'http' explicitly, but making requests over SSL. Removing this, or setting it to 'https' resolves the issue.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<sites>
<site patch:before="*[#name='website']"
name="my_website"
hostName="my_website.com"
scheme="http"
...
</sites>
</sitecore>
</configuration>
It's a known bug:
https://kb.sitecore.net/articles/913585
There is a patch for releases below 9.1 available here:
https://github.com/SitecoreSupport/Sitecore.Support.93141/releases
I agree with Jan's findings: setting externalPort on the site node in the configuration convinces Sitecore to exclude the port in a generated URL. I did a full write-up on my blog, including using the result for canonical URL tags.
http://findgnosis.com/2017/06/26/hiding-port-urls-produced-sitecores-linkmanager/
LinkManager:
You can cheat the LinkManager by adding port="443" externalPort="80" to your site-definition in <sites>. Don't know if this will cause other issues though.
<configuration>
<sitecore>
<sites>
<site name="website" port="443" externalPort="80" />
</sites>
</sitecore>
</configuration>
MediaManager:
If you know the url, set the Media.MediaLinkServerUrl-setting, to prevent Sitecore from creating the wrong url. Otherwise...
class SslFriendlyMediaProvider : MediaProvider
{
public override string GetMediaUrl(MediaItem item, MediaUrlOptions options)
{
var url = base.GetMediaUrl(item, options);
if(options.AlwaysIncludeServerUrl)
// https://example.com:443/a b?c=123 --> https://example.com/a%20b?c=123
return new Uri(url).AbsoluteUri;
return url;
}
}
Config:
<configuration xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<mediaLibrary>
<mediaProvider set:type="SslFriendlyMediaProvider, Assembly" />
</mediaLibrary>
</sitecore>
</configuration>
I am trying to create a session on MVC application
string roleName="Raj"
Session.Add("UserRole", roleName);
But in server i found that it throwing error as
Object reference not set to an instance of an object(I'm unable to create session in server)
Solutions i tried:
Administrator tools -> ASP.NET State Service -> Started
Please help me..
Is there any settings need to set on web.config
Do you have any reference to sessionState in your web.config file? If not, try this:
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webServer>
</configuration>
First, go to IIS.
Select Your Web Site
Select the Basic Setting in the right panel.
Select Connect as.
Select User Have permission to Site Folder