Why is my Post method disallowed? - c#

I've been successfully using this method to GET REST data:
private JArray GetRESTData(string uri)
{
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
return JsonConvert.DeserializeObject<JArray>(s);
}
catch // This method crashes if only one json "record" is found - try this:
{
try
{
MessageBox.Show(GetScalarVal(uri));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return null;
}
Between the webRequest and webResponse assignments, I added this:
if (uri.Contains("Post"))
{
webRequest.Method = "POST";
}
...and called it with this URI:
http://localhost:28642/api/Departments/PostDepartment/42/76TrombonesLedTheZeppelin
Although I have a Post method that corresponds to it:
Controller
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public void PostDepartment(string accountid, string name, string dbContext)
{
_deptsRepository.PostDepartment(accountid, name, dbContext);
}
Repository
public Department PostDepartment(string accountid, string name, string dbContext)
{
int maxId = departments.Max(d => d.Id);
// Add to the in-memory generic list:
var dept = new Department {Id = maxId + 1, AccountId = accountid, Name = name};
departments.Add(dept);
// Add to the "database":
AddRecordToMSAccess(dept.AccountId, dept.Name, dbContext);
return dept;
}
...it fails with, "The remote server returned an error: (405) Method Not Allowed."
Why is it not allowed?
UPDATE
Based on what I found here: http://blog.codelab.co.nz/2013/04/29/405-method-not-allowed-using-asp-net-web-api/, I added this to Web.Config:
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT"
type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
...so that it went from this:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*"
type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer></configuration>
...to this:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT"
type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer></configuration>
....but it made no diff.
UPDATE 2
It doesn't even make it to the call in the Controller:
[HttpPost]
[System.Web.Http.Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public void PostDepartment(string accountid, string name, string dbContext)
{
_deptsRepository.PostDepartment(accountid, name, dbContext);
}
I have a breakpoint inside it that's not reached...???
UPDATE 3
VirtualBlackFox's last comment was the one that did the trick. I just changed my "is it a post?" in my client code to the following:
if (uri.Contains("Post"))
{
webRequest.Method = "POST";
webRequest.ContentLength = 0; // <-- This line is all I added
}
...and now it works.

I don't do Asp.Net but i'll guess that you need to specify the HttpPost attribute as can be seen in Attribute Routing / HTTP Methods documentation :
[HttpPost]
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public void PostDepartment(string accountid, string name, string dbContext)
{
_deptsRepository.PostDepartment(accountid, name, dbContext);
}
Small sample that work on my PC :
TestController.cs:
using System.Web.Http;
namespace WebApplication2.Controllers
{
public class TestController : ApiController
{
[HttpPost]
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public string PostDepartment(string accountid, string name, string dbContext)
{
return accountid + name + dbContext;
}
}
}
Test.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(function () {
$.ajax("api/Departments/PostDepartment/accountid/name/dbContext", {
type: 'POST', success: function (data) {
$('#dest').text(data);
}
});
});
</script>
</head>
<body>
<div id="dest"></div>
</body>
</html>
Sample program to call the service in C# :
namespace ConsoleApplication1
{
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
class Program
{
static void Main()
{
Console.WriteLine(GetRestData(#"http://localhost:52833//api/Departments/PostDepartment/42/76TrombonesLedTheZeppelin"));
Console.ReadLine();
}
private static dynamic GetRestData(string uri)
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentLength = 0;
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
return JsonConvert.DeserializeObject<dynamic>(s);
}
}
}

Related

.Net, Azure routes other than index are not working, how do I fix this?

Part of my controller:
[HttpGet]
[Route("")]
public IActionResult Index()
{
return View();
}
[HttpGet]
[Route("/dragon")]
public IActionResult Dragon()
{
HttpContext.Session.Clear();
if(HttpContext.Session.GetObjectFromJson<Dachi>("Dachi") == null)
{
HttpContext.Session.SetObjectAsJson("Dachi", new Dachi());
}
Dachi dachi = HttpContext.Session.GetObjectFromJson<Dachi>("Dachi");
ViewBag.Fullness = dachi.fullness;
ViewBag.Happiness = dachi.happiness;
ViewBag.Meal = dachi.meal;
ViewBag.Energy = dachi.energy;
return View();
}
When I go to "myurl.azurewebsites.net/dragon"
It should start this simple dragon game.
However, I get a message that it is unable to handle its request.
My "" route (the Index) works fine.
Here is my web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\logs\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\stdout" forwardWindowsAuthToken="false"/>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
Why is my route other than Index not showing up???
Please help me. Thank you.
Do not use '\' on your route. Remove the same and it should work. To learn about routes - https://msdn.microsoft.com/en-us/library/cc668201.aspx#routes

System.Web.Routing.UrlRoutingModule does not implement IHttpHandlerFactory or IHttpHandler

In our Website this error is come every 5 minutes.
And I don't know from where its call.
we need robots.txt without this error.
our application automatic call http://www.xyzName.com/content/images/thumbs/robots.txt
And show below exception
System.Web.Routing.UrlRoutingModule does not implement
IHttpHandlerFactory or IHttpHandler.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
This is the method which automatic generate the robots.txt file when this method is call. but the problem is from some where in application robots.txt call automatically.
public ActionResult RobotsTextFile()
{
//Default Code blocked by Nilesh
if (_storeContext.CurrentStore.Url.Contains("tk"))
{
const string newLine = "\r\n"; //Environment.NewLine
var sb = new StringBuilder();
sb.Append("User-agent: *");
sb.Append(newLine);
sb.Append("Disallow: /");
Response.ContentType = "text/plain";
Response.Write(sb.ToString());
}
else
{
var disallowPaths = new List<string>
{
"/bin/",
"/content/files/",
"/content/files/exportimport/",
"/country/getstatesbycountryid",
"/install",
"/setproductreviewhelpfulness",
};
var localizableDisallowPaths = new List<string>
{
"/addproducttocart/catalog/",
"/addproducttocart/details/",
"/backinstocksubscriptions/manage",
"/boards/forumsubscriptions",
"/boards/forumwatch",
"/boards/postedit",
"/boards/postdelete",
"/boards/postcreate",
"/boards/topicedit",
"/boards/topicdelete",
"/boards/topiccreate",
"/boards/topicmove",
"/boards/topicwatch",
"/cart",
"/checkout",
"/checkout/billingaddress",
"/checkout/completed",
"/checkout/confirm",
"/checkout/shippingaddress",
"/checkout/shippingmethod",
"/checkout/paymentinfo",
"/checkout/paymentmethod",
"/clearcomparelist",
"/compareproducts",
"/customer/avatar",
"/customer/activation",
"/customer/addresses",
"/customer/changepassword",
"/customer/checkusernameavailability",
"/customer/downloadableproducts",
"/customer/info",
"/deletepm",
"/emailwishlist",
"/inboxupdate",
"/newsletter/subscriptionactivation",
"/onepagecheckout",
"/order/history",
"/orderdetails",
"/passwordrecovery/confirm",
"/poll/vote",
"/privatemessages",
"/returnrequest",
"/returnrequest/history",
"/rewardpoints/history",
"/sendpm",
"/sentupdate",
"/shoppingcart/productdetails_attributechange",
"/subscribenewsletter",
"/topic/authenticate",
"/viewpm",
"/uploadfileproductattribute",
"/uploadfilecheckoutattribute",
"/wishlist",
};
const string newLine = "\r\n"; //Environment.NewLine
var sb = new StringBuilder();
sb.Append("User-agent: *");
sb.Append(newLine);
//sitemaps
if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
{
//URLs are localizable. Append SEO code
foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
{
sb.AppendFormat("Sitemap: {0}{1}/sitemap.xml", _storeContext.CurrentStore.Url, language.UniqueSeoCode);
sb.Append(newLine);
}
}
else
{
//localizable paths (without SEO code)
sb.AppendFormat("Sitemap: {0}sitemap.xml", _storeContext.CurrentStore.Url);
sb.Append(newLine);
}
//usual paths
foreach (var path in disallowPaths)
{
sb.AppendFormat("Disallow: {0}", path);
sb.Append(newLine);
}
//localizable paths (without SEO code)
foreach (var path in localizableDisallowPaths)
{
sb.AppendFormat("Disallow: {0}", path);
sb.Append(newLine);
}
if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
{
//URLs are localizable. Append SEO code
foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
{
foreach (var path in localizableDisallowPaths)
{
sb.AppendFormat("Disallow: {0}{1}", language.UniqueSeoCode, path);
sb.Append(newLine);
}
}
}
Response.ContentType = "text/plain";
Response.Write(sb.ToString());
}
return null;
}
And In RouteProvider we add below line to map the route.
routes.MapRoute("robots.txt","robots.txt",new { controller = "Common", action ="RobotsTextFile" },new[] { "Nop.Web.Controllers" });
It comes in every 5 minuets. we use amazon server for CDN, get Images from there.
Is there any possibility that amazon called this 'http://www.xyzName.com/content/images/thumbs/robots.txt' url?
Remove (or comment out) this line from your web.config For generating robot.txt
<add name="RobotsTxt" path="robots.txt" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
And uncomment the following lines
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
Hope this helps!
I had this same issue after a recent publish of a Web API that I had recently changed the assembly name. I had no robots.txt file, so the above answers were not relevant to me. Anyway, as a solution, I simply cleaned out the folder on the server and republished.
I also had this issue on a fresh deployment to Server 2016. In the end, I actually commented out the handler mapping for URLRoutingModule and it worked. My guess is it was conflicting with something already set on the machine level.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<!--<remove name="UrlRoutingModule-4.0"/>
<add name="UrlRoutingModule-4.0" path="*" verb="*" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>-->
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

httpModule in App_code will not load when debugging locally

I have a simple .net web application and implemented a class based off of IHttp. I copied the example directly from Microsoft documentation. The class is located in the app_code directory.
The problem is that whenever I run the application I get the following error:
HttpException (0x80004005): Could not load type 'httpModuleEx.App_Code.HelloWorldClass'
Here is my web.config entry to register the new class:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<remove name="HelloWorldClass"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
<add name="HelloWorldClass" type="httpModuleEx.App_Code.HelloWorldClass"/>
</modules>
</system.webServer>
I have tried many variations on referencing the HelloWorldClass here but none worked for me.
I also tried making the build action of the HelloWorldClass.cs file (located under the app_code directory) "compile".
Below is the code from the HelloWorldClass.cs file:
using System;
using System.Web;
namespace httpModuleEx.App_Code
{
public class HelloWordClass : IHttpModule
{
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
application.EndRequest += (new EventHandler(this.Application_EndRequest));
}
private void Application_BeginRequest(Object source, EventArgs args)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<h1><font color=red>" +
"HelloWorldModule: Beginning of Request" +
"</font></h1><hr>");
}
}
private void Application_EndRequest(Object source, EventArgs args)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<hr><h1><font color=red>" +
"HelloWorldModule: End of Request</font></h1>");
}
}
public void Dispose()
{
}
}
}
Any help would be greatly appreciated.
Could it be because you've spelled World as Word in your code :)
Yes. Thank you! Also I changed the web.config to:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<remove name="HelloWorldClass"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
<add name="HelloWorldClass" type="httpModuleEx.App_Code.HelloWorldClass, httpModuleEx"/>
</modules>
</system.webServer>

DELETE request not allowed using CORS for cross domain request with angularjs

I've created a site based on the demo of http://bitoftech.net/
I've gotten everything to work just fine, however, for some reason requests other than POST or GET get blocked when the OPTION request is made to my api.
I get the following error for the below request:
http://localhost:26264/api/photo/facebook_reactions-02.png
XMLHttpRequest cannot load http://localhost:26264/api/photo/facebook_reactions-02.png. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:32150' is therefore not allowed access. The response had HTTP status code 404
I receive the above error when the following code is executed:
'remove': { method: 'DELETE', url: serviceBase + 'api/photo/:fileName', params: { name: '#fileName' } }
The localhost is the correct one. If I do a post that contains data I can get through. E.g. when I want to update user data through a POST.
The demo app also contains an interceptor authInterceptorService.js so that my requests get handled before it's send.
var _request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('authorizationData');
if (authData) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
But when I look at the request:
OPTIONS /api/photo/facebook_reactions-02.png HTTP/1.1
Host: localhost:26264
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: DELETE
Origin: http://localhost:32150
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://localhost:32150/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: nl,en-US;q=0.8,en;q=0.6,fr;q=0.4
I don't see the content-type separately nor as part of Access-Control-Request-Headers.
The strange thing is, in the response I see the following:
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS, TOKEN
So I'd think my request gets through. But, it doesn't...
For completeness sake my StartUp.cs:
[assembly: OwinStartup(typeof(AngularJSAuthentication.API.Startup))]
[...]
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
Database.SetInitializer(new MigrateDatabaseToLatestVersion<AuthContext, Migrations.Configuration>());
}
public void ConfigureOAuth(IAppBuilder app)
{
//use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() {
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new SimpleAuthorizationServerProvider(),
RefreshTokenProvider = new SimpleRefreshTokenProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
And the web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="UrlRoutingModule-4.0" path="*." verb="*" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS, TOKEN" />
</customHeaders>
</httpProtocol>
</system.webServer>
What am I overlooking to allow DELETE (as well as PUT) requests to get through?
Issue found!
When trying to do an OPTIONS/a DELETE request with a string that ends with an extension, such as an image, like the following request:
http://localhost:26264/api/photo/facebook_reactions-02.png
It is not allowed to do so because it can't map it to the web api controller method which is
[HttpDelete]
[Route("{fileName}")]
public async Task<IHttpActionResult> Delete(string fileName)
I presume this is because the logic thinks I want to request an image.
To bypass this I changed the dot to a dash and in my code do a replace like so:
var lastDashPosition = fileName.LastIndexOf('-');
var fileNameSegment = fileName.Substring(0, lastDashPosition);
var extensionSegment = fileName.Substring(lastDashPosition+1);
fileName = string.Format("{0}.{1}", fileNameSegment, extensionSegment);
Following the above I handle the file as per usual:
if (!photoManager.FileExists(fileName))
{
return NotFound();
}
var result = await photoManager.Delete(fileName);
if (result.Successful)
{
return Ok(
new {
message = result.Message
}
);
}
else
{
return BadRequest(result.Message);
}
The above works like a charm and since you need to be authorized to execute the delete and it's an image I wish to delete I can safely presume that the final dish of the string is the dash I must replace with a dot.

httpModules not working on iis7

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>

Categories