I have a self hosted Rest Service and users are reporting getting 413 errors when uploading large images. It works with smaller strings
The images are being sent as a base64 encoded string.
I have a feeling it is something to do with a default limit that I need to increase from some other threads I have read.
But I have been unable to work out what an where I need to add the configuration?
Do I need to add it to the App.config?
This is my current App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Service.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
<section name="HttpApiService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<userSettings>
<Service.Properties.Settings>
<setting name="URL" serializeAs="String">
<value>https://localhost:8083/</value>
</setting>
</Service.Properties.Settings>
<HttpApiService.Properties.Settings>
<setting name="URL" serializeAs="String">
<value>https://localhost:8083/</value>
</setting>
</HttpApiService.Properties.Settings>
</userSettings>
</configuration>
I have the feeling it is something along the lines of:
<system.serviceModel>
<webHttpBinding>
<binding
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" transferMode="Streamed">
</binding>
</webHttpBinding>
But wherever I try to add that section into my app.config I get an error.
Can anyone tell me how to solve this 413 problem in a self hosted service?
I believe this is the answer...
_config.MaxReceivedMessageSize = 5242880; // 5mb
_config.MaxBufferSize = 5242880; // 5mb
In the following:
namespace HttpApiService
{
public partial class HttpApiService : ServiceBase
{
private HttpSelfHostServer _server;
//private readonly HttpSelfHostConfiguration _config; // http
private readonly MyHttpsSelfHostConfiguration _config; // https
public string ServiceAddress = Settings.Default.URL;
public HttpApiService()
{
InitializeComponent();
_config = new MyHttpsSelfHostConfiguration(ServiceAddress);
_config.MapHttpAttributeRoutes();
_config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional });
// added these to solve the upload size problem
_config.MaxReceivedMessageSize = 5242880; // 5mb
_config.MaxBufferSize = 5242880; // 5mb
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("HttpApiService started.");
_server = new HttpSelfHostServer(_config);
_server.OpenAsync();
}
protected override void OnStop()
{
EventLog.WriteEntry("HttpApiService stopped.");
_server.CloseAsync().Wait();
_server.Dispose();
}
class MyHttpsSelfHostConfiguration : HttpSelfHostConfiguration
{
public MyHttpsSelfHostConfiguration(string baseAddress) : base(baseAddress) { }
public MyHttpsSelfHostConfiguration(Uri baseAddress) : base(baseAddress) { }
protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
{
httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
//Console.WriteLine("https is on");
return base.OnConfigureBinding(httpBinding);
}
}
}
}
Related
I like to store a username and password to the user.config in my C# .net5 program. I don't want to store the password direct and I decided to decrypt the userSettings section.
After decryption parts of the file are missing.
Orginal user.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" >
<section name="FileUploader.Properties.Settings" type="System.Configuration.ClientSettingsSection, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToLocalUser" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<FileUploader.Properties.Settings>
<setting name="UserName" serializeAs="String">
<value>user</value>
</setting>
<setting name="Password" serializeAs="String">
<value>xyz</value>
</setting>
</FileUploader.Properties.Settings>
</userSettings>
</configuration>
After encryption:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" >
<section name="FileUploader.Properties.Settings" type="System.Configuration.ClientSettingsSection, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToLocalUser" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<FileUploader.Properties.Settings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA4LmAfRMCHUeURwT1gTPd8AQAAAACAAAAAAAQZgAAAAEAACAAAADnR+uFolwsH4gkWI6vd46HNUxBv7ZfrQJmHe0q/zz8jAAAAAAOgAAAAAIAACAAAABlvfcY6M7JdG2dKIXO7cUUO9ui3Nou40CjMolKyJW7zgACAAAL5H+KJFPGoyugYYFDkZsV7GjXoaO+r8/z01/OiqVYXw80dCUIKje2g0tgizNrB/rAUmSg/uDPBx1yj3TAJ5aXf+fRxJaspf1jjr+QIaSJShnpy1sEjjpbUUn9+BVCYSJH8d4Ysj2JP1wvM5mgFBlFUcCLhHO+FputK3XpihAZCXeOddjNw2xYIQu4pmenLBiW6+fRUpINmNan/exQvHOWfwXuoZvqUli1hv+29qTuh/eJuPJQoyQSKrZ1A6Ie8aG2dsgQDvnVFEkt8cChkTn/TIc2Dk1uSDrsIYj/Ah8g1T5bE3PvWAYv67vtEfKbwBrqig+3HOSltZayVWyd2Y7iDS15Qk763ipiaBM64zhs/g4koQWpH1kAkfqgW3ibYAJEsk1a/K0Dd1Q2muxo0fsk1DfNYJIhFS8eAIuABlF6NAF5AT5hYyIOWVGjaquEP/aqzepCjEwkoLgD003qMISK7W6EAugSbWCRTwcMcKxZD3tHTmNLzZk+g8C7XpaWOk0xyODi5+mVXI8zg7NIGYo34JPado8l0p0Qd0gx15PwtZNHj0k9o6rieTgWjJEqf52ng70DNySsSX3jfyW91ArslcMLqO1qpbSFuIt0LeIswSxoR/etNM+GoGUjRW7t1OKGLcV5Wi8k0QdheXhxo6Hvq2/nv9iFYJxqgwoN6v1N0kAAAAACcCtrS9KBGCutdHdYddlimN5cPb8+X/snuKEgu63fi4TE2VSei4R0WqjeC22JIFn3HqPIzWb9Kd9pPDJCWQz7</CipherValue>
</CipherData>
</EncryptedData>
</FileUploader.Properties.Settings>
</userSettings>
</configuration>
After decryption:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" >
<section name="FileUploader.Properties.Settings" type="System.Configuration.ClientSettingsSection, System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToLocalUser" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<FileUploader.Properties.Settings>
<setting name="" serializeAs="String">
<value>xyz</value>
</setting>
</FileUploader.Properties.Settings>
</userSettings>
</configuration>
There is only the last entry and the name of the entry is missing. If I switch the order in the original file, I get "user" as the value.
The code to decrypt/encrypt (more or less a copy of an msdn example):
private void ProtectSettings()
{
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
// Define the Rsa provider name.
string provider = "DataProtectionConfigurationProvider";
string section = "userSettings/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Properties.Settings";
// Get the section to protect.
ConfigurationSection connStrings = config.GetSection(section);
if (connStrings != null)
{
if (!connStrings.SectionInformation.IsProtected)
{
if (!connStrings.ElementInformation.IsLocked)
{
// Protect the section.
connStrings.SectionInformation.ProtectSection(provider);
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
Debug.WriteLine("Section {0} is now protected by {1}",
connStrings.SectionInformation.Name,
connStrings.SectionInformation.ProtectionProvider.Name);
}
else
Debug.WriteLine(
"Can't protect, section {0} is locked",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine(
"Section {0} is already protected by {1}",
connStrings.SectionInformation.Name,
connStrings.SectionInformation.ProtectionProvider.Name);
}
else
Debug.WriteLine("Can't get the section {0}", section);
}
private static void UnProtectSettings()
{
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
string section = "userSettings/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Properties.Settings";
// Get the section to unprotect.
ConfigurationSection connStrings = config.GetSection(section);
if (connStrings != null)
{
if (connStrings.SectionInformation.IsProtected)
{
if (!connStrings.ElementInformation.IsLocked)
{
// Unprotect the section.
connStrings.SectionInformation.UnprotectSection();
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
Debug.WriteLine("Section {0} is now unprotected.",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine(
"Can't unprotect, section {0} is locked",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine(
"Section {0} is already unprotected.",
connStrings.SectionInformation.Name);
}
else
Debug.WriteLine("Can't get the section {0}", section);
}
After playing around with this for a while, I discovered that the issue comes from the ConfigurationSaveMode.Full option.
In both ProtectSettings() and UnProtectSettings(), instead of
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
simply use:
config.Save();
I have no idea why that option leads to unwanted behavior.
Below is my try to use Memcache in a console application.
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="enyim.com"/>
<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection,Enyim.Caching"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<enyim.com>
<memcached protocol="Binary">
<severs>
<add address="127.0.0.1" port="11211"/>
</severs>
</memcached>
</enyim.com>
</configuration>
C#
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
try
{
using (MemcachedClient memcache = new MemcachedClient())
{
string cachedTime = memcache.Get<string>("CachedTime");
if (cachedTime == null)
{
memcache.Store(Enyim.Caching.Memcached.StoreMode.Set, "CachedTime", DateTime.Now.ToString());
cachedTime = memcache.Get<string>("CachedTime");
}
Console.WriteLine(cachedTime);
Console.WriteLine(dt);
}
}
catch (Exception ex)
{
}
}
Every time the value of cachedDate is NULL
Change App.Config to the following and it should work:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="enyim.com">
<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<enyim.com>
<memcached>
<servers>
<add address="127.0.0.1" port="11211" />
</servers>
<socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />
</memcached>
</enyim.com>
</configuration>
I am trying to create a WCF client APP that is consuming a JAVA WS that uses three certificates of which two of them aer for signing and encryption and one is for transport. There is a private key that is installed on the server and a public certificate file was exported from the JKS keystore file. I have installed the public key and keys for signing and encryption into certificate store via MMC under Personal certificates.
Here is My Code from Form:
public Form1()
{
InitializeComponent();
ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls;
referencaServisa.obrtniWsServiceClient klijent = new referencaServisa.SomeServiceClient();
var vs = klijent.Endpoint.Behaviors.Where((i) => i.GetType().Namespace.Contains("VisualStudio"));
klijent.Endpoint.Behaviors.Remove((System.ServiceModel.Description.IEndpointBehavior)vs.Single());
klijent.Endpoint.Address = new System.ServiceModel.EndpointAddress(#"https://213.147.119.174:4444/some-registar-ws/someWsService");
CustomBinding binding = new CustomBinding();
SecurityBindingElement sbe = SecurityBindingElement.CreateMutualCertificateDuplexBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
AsymmetricSecurityBindingElement asymetricElement=(AsymmetricSecurityBindingElement)sbe;
asymetricElement.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128Rsa15;
asymetricElement.ProtectTokens = true;
asymetricElement.IncludeTimestamp = false;
asymetricElement.SetKeyDerivation(false);
asymetricElement.EnableUnsecuredResponse = true;
asymetricElement.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
asymetricElement.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
asymetricElement.AllowSerializedSigningTokenOnReply=true;
X509SecurityTokenParameters initiator = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.SubjectKeyIdentifier, SecurityTokenInclusionMode.AlwaysToInitiator);
/*X509SecurityTokenParameters recipient = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.RawDataKeyIdentifier, SecurityTokenInclusionMode.AlwaysToInitiator);
asymetricElement.RecipientTokenParameters = recipient;
asymetricElement.InitiatorTokenParameters = initiator;
asymetricElement.InitiatorTokenParameters.RequireDerivedKeys = false;*/
asymetricElement.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt;
asymetricElement.LocalClientSettings.IdentityVerifier = new MyIdentityVerifier();
asymetricElement.EndpointSupportingTokenParameters.Signed.Add(
new X509SecurityTokenParameters());
binding.Elements.Clear();
binding.Elements.Add(asymetricElement);
CustomTextMessageBindingElement customTextMessageBindingElement = new CustomTextMessageBindingElement("UTF-8", "text/xml", MessageVersion.Soap11);
binding.Elements.Add(customTextMessageBindingElement);
HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement
{
RequireClientCertificate=true
};
httpsTransportBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
httpsTransportBindingElement.TransferMode = TransferMode.Buffered;
httpsTransportBindingElement.UseDefaultWebProxy = true;
httpsTransportBindingElement.KeepAliveEnabled=true;
httpsTransportBindingElement.AuthenticationScheme = AuthenticationSchemes.Digest;
httpsTransportBindingElement.RequireClientCertificate = true;
binding.Elements.Add(httpsTransportBindingElement);
klijent.Endpoint.Binding = binding;
referencaServisa.statusType status;
string poruka;
referencaServisa.registarskiUlozak[] registarskiUlosci;
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
// Begin using the client.
try
{
klijent.Open();
status = klijent.getUlosciByMbo("90445066",false, out poruka, out registarskiUlosci);
referencaServisa.ulozak receivedUlozak = null;
if (status.ToString() == "OK")
{
receivedUlozak = registarskiUlosci[0].aktivnoStanjeUloska.ulozak;
MessageBox.Show(receivedUlozak.vlasnici[0].redniBroj.ToString());
}
MessageBox.Show(status.ToString());
// Close the client.
klijent.Close();
}
catch (ProtocolException ex) { MessageBox.Show(ex.Message); }
}
So I use three certificates one for signing one for encryption and one for SSL transport. I use custom binding for separation of certificates. When I start my app I get an error General security error:
The content type text/xml;charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=UTF-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 394 bytes of the response were: '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">ns1:InvalidSecurity</faultcode><faultstring>An error was discovered processing the <wsse:Security> header (Unsupported key identification)</faultstring></soap:Fault></soap:Body></soap:Envelope>'.
Here is my app.config :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="dasda12312.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="false"/>
</settings>
</system.net>
<system.diagnostics>
<switches>
<add name="Remote.Disable" value="1"/>
</switches>
</system.diagnostics>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="MyClientCredentialsExtension">
<MyClientCredentialsExtension>
<clientCertificate findValue="removed" storeLocation="LocalMachine" x509FindType="FindBySerialNumber" storeName="My" />
<serviceCertificate>
<defaultCertificate findValue="removed" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
</serviceCertificate>
<transportCertificate findValue="removed" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySerialNumber"/>
</MyClientCredentialsExtension>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="cb">
<security authenticationMode="MutualCertificate" requireDerivedKeys="true" includeTimestamp="true"
allowSerializedSigningTokenOnReply="true" securityHeaderLayout="Lax"
defaultAlgorithmSuite="Basic256"
keyEntropyMode="ClientEntropy" requireSecurityContextCancellation="false"
messageProtectionOrder="SignBeforeEncrypt" messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10" />
<textMessageEncoding messageVersion="Soap11" />
<httpsTransport />
</binding>
</customBinding>
<client>
<!---->
<endpoint address=""
behaviorConfiguration="MyClientCredentialsExtension" binding="customBinding" bindingConfiguration="cb"
contract="referencaServisa.someWsService"
name="SomeWsServiceImplPort">
</endpoint>
</client>
<extensions>
<behaviorExtensions>
<add name="MyClientCredentialsExtension" type="SEOP.MyClientCredentialsExtensionElement,dasda12312"/>
</behaviorExtensions>
</extensions>
</system.serviceModel>
<applicationSettings>
<dasda12312.Properties.Settings>
<setting name="dasda12312_someReferenca2_someWsService" serializeAs="string">
<value>https://213.147.119.174:4444/some-registar-ws/someWsService</value>
</setting>
</dasda12312.Properties.Settings>
</applicationSettings>
</configuration>
Anyone had similar problem please help me and tell me how to fix this.
Thank you.
I'm a quite beginner with config sections in c#
I want to create a custom section in config file. What I've tried after googling is as the follows
Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyCustomSections">
<section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
</sectionGroup>
</configSections>
<MyCustomSections>
<CustomSection key="Default"/>
</MyCustomSections>
</configuration>
CustomSection.cs
namespace CustomSectionTest
{
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
[StringValidator(InvalidCharacters = "~!##$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public String Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
}
}
When I use this code to retrieve Section I get an error saying configuration error.
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
What am I missing?
Thanks.
Edit
What I need ultimately is
<CustomConfigSettings>
<Setting id="1">
<add key="Name" value="N"/>
<add key="Type" value="D"/>
</Setting>
<Setting id="2">
<add key="Name" value="O"/>
<add key="Type" value="E"/>
</Setting>
<Setting id="3">
<add key="Name" value="P"/>
<add key="Type" value="F"/>
</Setting>
</CustomConfigSettings>
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="customAppSettingsGroup">
<section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</sectionGroup>
</configSections>
<customAppSettingsGroup>
<customAppSettings>
<add key="KeyOne" value="ValueOne"/>
<add key="KeyTwo" value="ValueTwo"/>
</customAppSettings>
</customAppSettingsGroup>
</configuration>
Usage:
NameValueCollection settings =
ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings")
as System.Collections.Specialized.NameValueCollection;
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Response.Write(key + ": " + settings[key] + "<br />");
}
}
Try using:
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("MyCustomSections/CustomSection");
You need both the name of the section group and the custom section.
Highlight ConfigurationSection press F1,
You will see that the implementation on the MSDN website overrides a property called "Properties" which returns a "ConfigurationPropertyCollection", as your properties have a matching attribute of that type you should be able to populate this collection with your properties if not wrap them in the same way the MS guys have.
I have the following module
public class LowerCaseRequest : IHttpModule {
public void Init(HttpApplication context) {
context.BeginRequest += new EventHandler(this.OnBeginRequest);
}
public void Dispose() { }
public void OnBeginRequest(Object s, EventArgs e) {
HttpApplication app = (HttpApplication)s;
if (app.Context.Request.Url.ToString().ToLower().EndsWith(".aspx")) {
if (app.Context.Request.Url.ToString() != app.Context.Request.Url.ToString().ToLower()) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower();
response.SuppressContent = true;
response.End();
}
if (!app.Context.Request.Url.ToString().StartsWith(#"http://zeeprico.com")) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower().Replace(#"http://zeeprico.com", #"http://www.zeeprico.com");
response.SuppressContent = true;
response.End();
}
}
}
}
the web.config looks like
<system.web>
<httpModules>
<remove name="WindowsAuthentication" />
<remove name="PassportAuthentication" />
<remove name="AnonymousIdentification" />
<remove name="UrlAuthorization" />
<remove name="FileAuthorization" />
<add name="LowerCaseRequest" type="LowerCaseRequest" />
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
It works grate on my PC running XP and IIS 5.1
but on my webserver running IIS7 and WS 2008 dosn't works, please help I don't know how to work this out.
Thanks
On IIS7 and higher use
<configuration>
<system.webServer>
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
</system.webServer>
</configuration>
Above is correct for IIS 7.5
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
the only problem I got, is that instance of application pool for particular application should be set to managed Pipeline = Integrated, not Classic..
or:
Using Classic Mode
If your application is to use Classic mode, then make sure that your application is configured for that type of pool and your modules are configured in system.web section and not in system.webServer section of web.config file.
In IIS go to feature view select module
double click to module then right click and press (Add Managed Module)
then put name and type as defined in web.config
example:
<httpModules>
<add name="CustomModule" type="WebApplication.Security.CustomModule" />
</httpModules>