Hi I am using an HttpModule to call WebAPI. Currently the solution is working locally in the system but once i published the code in Server,it fails to make the API call.Here is the Sample Code:
public class AppModule: IHttpModule
{
public void Init(HttpApplication httpApp)
{
httpApp.BeginRequest += OnBeginRequest;
httpApp.EndRequest += OnEndRequest;
httpApp.PreSendRequestHeaders += OnHeaderSent;
}
public void OnBeginRequest(Object sender, EventArgs e)
{
try
{
var httpApp = (HttpApplication)sender;
if (httpApp.Request.Path.StartsWith("/media/")) return;
string a = httpApp.Request.ServerVariables["ID"];
if (String.IsNullOrEmpty(a))
{
a = System.Configuration.ConfigurationManager.AppSettings["ID"];
}
var absolutepath = httpApp.Request.Url.AbsolutePath;
var values = new Dictionary<string, object>
{
{ "ID", a },
{ "Browser",httpApp.Request.Browser["Type"] },
{ "Url",httpApp.Request.Url.Scheme + "://" + httpApp.Request.Url.Authority + absolutepath},
{ "OperatingSys",httpApp.Request.Headers["User-Agent"] },
{ "IPAddss",httpApp.Request.UserHostAddress },
{ "LDate",System.DateTime.Now.ToString() },
};
var serializer = new JavaScriptSerializer();
var appData = serializer.Deserialize<DataVO>(serializer.Serialize(values));
AppModuleVO objAppModuleVO = new AppModuleVO();
//AppModuleVo has all the properties.
objAppModuleVO.WebUrl = System.Configuration.ConfigurationManager.AppSettings["APIURL"] + MethodCall;
objAppModuleVO.objDataVo = appData;
ThreadPool.QueueUserWorkItem(new WaitCallback(HandlePostRequest), objAppModuleVO);
}
catch (Exception ex)
{
}
}
}
I have registered the same in Web.Config as
<system.web>
<httpModules>
<add name="AppModule" type="Fighter.Modules.AppModule"/>
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="AppModule" type="Fighter.Modules.AppModule"/>
</modules>
</system.webServer>
I am not sure whether any changes or registration needs to be made in the IIS server after publishing the code in server.Note: I have also deployed the API in the server and provided the correct path and since other methods can call the same API that is ruled out. Please help .The problem seems to be because of the IIS currently I am using IIS 7.0 in Managed Pipeline mode as CLASSIC.Any workarounds for this issue.
To long for a comment so... try this in your web.config:
....
<system.webServer>
<modules>
<add name="AppModule" type="Fighter.Modules.AppModule"/>
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Having said that you should consider using IntegratedMode.
Related
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>
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>
Appologise if this has already been asked but I have an asp.net website and all my footer pages are stored in Visual Studio under
Views > Footer > [Page Names]
When i click on a footer link, my URL is displaying as:
http://www.mysite.co.uk/Views/Footer/testpage
What i'm after is removing the "/Views/Footer" from the URL so it loks like:
http://www.mysite.co.uk/testpage
I have no idea how to do this. Could someone please give me step by step guide on code to use and where to put it so that it does this.
when ever i try double clicking on my Global.asax file it automatically opens the Global.asax.cs file which i suspect is also wrong
Add reference to system.web.routing to project
add urlroutingmodule to http module in config:
<configuration>
...
<system.web>
...
<httpModules>
...
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
...
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
<handlers>
...
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
...
</system.webServer>
</configuration>
Define routes in global.asax:
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
// Register a route for Categories/All
routes.Add(
"All Categories",
new Route("Categories/All", new CategoryRouteHandler())
);
// Register a route for Categories/{CategoryName}
routes.Add(
"View Category",
new Route("Categories/{*CategoryName}", new CategoryRouteHandler())
);
// Register a route for Products/{ProductName}
routes.Add(
"View Product",
new Route("Products/{ProductName}", new ProductRouteHandler())
);
}
Create route handler classes
public class ProductRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string productName = requestContext.RouteData.Values["ProductName"] as string;
if (string.IsNullOrEmpty(productName))
return Helpers.GetNotFoundHttpHandler();
else
{
// Get information about this product
NorthwindDataContext DataContext = new NorthwindDataContext();
Product product = DataContext.Products.Where(p => p.ProductName == productName).SingleOrDefault();
if (product == null)
return Helpers.GetNotFoundHttpHandler();
else
{
// Store the Product object in the Items collection
HttpContext.Current.Items["Product"] = product;
return BuildManager.CreateInstanceFromVirtualPath("~/ViewProduct.aspx", typeof(Page)) as Page;
}
}
}
}
create asp.net pages that process request:
protected void Page_Load(object sender, EventArgs e)
{
dvProductInfo.DataSource = new Product[] { Product };
dvProductInfo.DataBind();
}
protected Product Product
{
get
{
return HttpContext.Current.Items["Product"] as Product;
}
}
This is a good reference to work off, I have used this in the past on webforms apps and it worked like a charm.
If you're not using MVC, then you can implement an IHttpModule. There are several guides on the Internet on how to do this, such as Scott Guthrie's here: http://weblogs.asp.net/scottgu/tip-trick-url-rewriting-with-asp-net
I have an HTTP Module that I installed on our server. What's weird is that it works but every once in awhile it's not being executed. I have logging and during the times that it doesn't work it doesn't reach the code that logs. I don't see anything in the IIS logs or the event viewer either.
namespace RedirectModule
{
public class RedirectModule : System.Web.IHttpModule
{
private const string MobileUserAgent = "MobileUserAgentCacheKey";
private const string
STRING_TO_FIND = "info/lps";
private const string STRING_TO_ADD = "/mobile";
public void Dispose()
{
//clean-up code here.
}
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}
private static object sync = new object();
private void context_BeginRequest(object sender, EventArgs e)
{
try
{
HttpContext context = HttpContext.Current;
string url = context.Request.Url.ToString().ToLower();
if (!url.Contains(STRING_TO_FIND) || url.Contains(STRING_TO_FIND + STRING_TO_ADD))
return;
Logger.Current.Log("Starting Redirect Phase");
if (XmlToValues.IsMobile(context.Request.ServerVariables["HTTP_USER_AGENT"],
GetCachedFile(context, "Settings.xml")))
{
var mobileRedirect = GetRedirectUrl(url, STRING_TO_FIND, STRING_TO_ADD);
if (mobileRedirect != null)
{
Logger.Current.Log("Redirect to Mobile page");
context.Response.Redirect(mobileRedirect);
}
}
Logger.Current.Log("Web Page");
Logger.Current.Log("End Begin Request");
}
catch (Exception ex)
{
if (ex is ThreadAbortException)
return;
Logger.Current.LogError(ex);
}
}
public static string GetRedirectUrl(string url, string strToFind, string strToAdd)
{
try
{
Logger.Current.Log("Get Redirect Url ");
int idx = url.IndexOf(strToFind) + strToFind.Length;
return url.Substring(0, idx) + strToAdd + url.Substring(idx);
}
catch (Exception ex)
{
Logger.Current.LogError(ex);
return null;
}
}
private XmlNodeList GetCachedFile(HttpContext context, string filePath)
{
try
{
Logger.Current.Log("GetCachedFile START");
if (context.Cache[MobileUserAgent] == null)
{
context.Cache[MobileUserAgent] = XmlToValues.GetMobileUserAgents(filePath);
Logger.Current.Log("Add Mobile File to Cache");
}
return (XmlNodeList)context.Cache[MobileUserAgent];
}
catch (Exception ex)
{
Logger.Current.LogError(ex);
return null;
}
}
}
}
and my Web.Config:
<?xml version="1.0" encoding="UTF-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="RedirectModule" />
<add name="RedirectModule" type="RedirectModule.RedirectModule, RedirectModule" />
</modules>
<handlers>
<remove name="Redirect" />
</handlers>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
<system.web>
<httpModules>
<add name="RedirectModule" type="RedirectModule.RedirectModule, RedirectModule" />
</httpModules>
<compilation debug="true">
</compilation>
</system.web>
</configuration>
p.s. I took out the log4net in the web.config as it's cumbersome.
Here's the link to the project: http://www.sendspace.com/file/w42me5
This is the markup of the page being requested, it's in a file called index.htmnl:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<!-- no cache headers -->
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Cache-Control" content="no-cache">
<!-- end no cache headers -->
</head>
<body>
MOBILE
</body>
</html>
I had a similar prblem... Try to turn of caching in your webbrowser and try again. In order to turn off caching for this requests youll need to modify response header. Example on modifying caching option
It sounds like you're probably hitting a cache somewhere between the browser and the server. There's a lot of potential places for the cache to be, here's some general steps to try and find it:
Browser - The browser does not have to request what it has cached. This question lists tools for different browsers to confirm what requests are being sent.
Client Computer - If a request is being sent from the browser, you may have a proxy (like Squid) returning cached data. You can use Fiddler to check if a HTTP request ever leaves the client computer.
Network Proxy - Same idea as the client computer, just the proxy is located on a server somewhere on your network. You would have to analyze outgoing HTTP traffic at the proxy server to determine if a request is being sent or not.
Web Server - Your redirect module can serve cached content instead of rendering it new. In this case, it should show up in your logs. Add a log call to the very beginning of your BeginRequest handler to confirm if the request actually makes it to your server.
To prevent caching, you can add add no-cache headers to the request (article here):
private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.ExpiresAbsolute = DateTime.Now.AddDays( -100 );
context.Response.AddHeader( “pragma”, “no-cache” );
context.Response.AddHeader( “cache-control”, “private” );
context.Response.CacheControl = “no-cache”;
}
EDIT
Debugging what request get to the server
HTTP 200 in the response suggests that it's very likely you do not have a cache issue. To confirm every request is actually getting to the server, try adding a log to your Application_BeginRequest handler (in Global.asax) to log every request and compare it to the log generated by your context_BeginRequest in your HttpModule.
//In Global.asax
private void Application_BeginRequest(Object source, EventArgs e) {
Logger.Current.Log("Request made to Application_BeginRequest")
}
//In your HttpModule
private void context_BeginRequest(object sender, EventArgs e)
{
//Log before any of your other code
Logger.Current.Log("Request made to context_BeginRequest")
try
{
// your code
}
catch (Exception ex)
{
// log the exception first in case this is the problem
Logger.Current.LogError(ex);
if (ex is ThreadAbortException)
return;
}
}
Interpreting the results
Check your log after a request that is not getting to your module.
If it shows nothing, the request never made it to your server. See above about caches
If your log end at Request made to Application_BeginRequest, your module is not being called.
If it ends at Request made to context_BeginRequest, there's an error in the module code before your logger which is causing a crash on some requests. This could be a null reference HttpContext.Current, or Request, or a problem with overflows, or any number of other things. This should be logged by your finally statement.
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>