Implement autofac in asp.net web form - c#

I am developing ASP.net Web Form, and I want to implement AutoFac into the website.
I have followed the steps in following link:
https://autofaccn.readthedocs.io/en/latest/integration/webforms.html
But I got this error:
This module requires that the HttpApplication (Global Application Class) implements IContainerProviderAccessor.
I can't find Global.asax.cs in my project, only Global.asax.
Global.asax:
<%# Application Language="C#" %>
<%# Import Namespace="Autofac" %>
<%# Import Namespace="Autofac.Integration.Web" %>
<script RunAt="server">
public class Global : HttpApplication, IContainerProviderAccessor {
// Provider that holds the application container.
static IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public IContainerProvider ContainerProvider {
get { return _containerProvider; }
}
void Application_Start(object sender, EventArgs e) {
// Code that runs on application startup
// Build up your application container and register your dependencies.
var builder = new ContainerBuilder();
//builder.RegisterType<SomeDependency>();
// ... continue registering dependencies...
// Once you're done registering things, set the container
// provider up with your registrations.
_containerProvider = new ContainerProvider(builder.Build());
}
}
</script>
Any ideas? Thank you very much!

I had this problem too and fixed it by creating a global.asax.cs file and referencing this from the original global.asax file. This enables you to implement the required IContainerProviderAccessor interface.
File: Global.asax
<%# Application Codebehind="Global.asax.cs" Inherits="MyCompany.WebForms.Global" Language="C#" %>
File: Global.asax.cs
using Autofac;
using Autofac.Core;
using Autofac.Integration.Web;
using ....
namespace MyCompany.WebForms
{
public partial class Global : HttpApplication, IContainerProviderAccessor
{
// Provider that holds the application container.
static IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
protected void Application_Start(object sender, EventArgs e)
{
....
}
}
}
After implementing this, I also had problems with Could not load type 'MyCompany.WebForms.Global' errors until I moved Global.asax.cs file into the App_Code folder and updated the CodeBehind reference Global.asax.

<configuration>
<system.web>
<httpModules>
<!-- This section is used for IIS6 -->
<add
name="ContainerDisposal"
type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
<add
name="PropertyInjection"
type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/>
</httpModules>
</system.web>
<system.webServer>
<!-- This section is used for IIS7 -->
<modules>
<add
name="ContainerDisposal"
type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"
preCondition="managedHandler"/>
<add
name="PropertyInjection"
type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"
preCondition="managedHandler"/>
</modules>
</system.webServer>
</configuration>
These sections must be defined in the web.config file in order for injection to work.
See https://code.google.com/p/autofac/wiki/WebFormsIntegration#Implement_IContainerProviderAccessor_in_Global.asax

Related

My Hub class is not calling using signal R

I am using signalR in my application.
This the client side code:
<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-2.2.0.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
var data = $.connection.Hubclass;
alert(data); // data is undefine
</script>
My hub class is as bellow
public class Hubclass :Hub
{
public void getdata(string msg)
{
Clients.All.send(msg);
}
}
I have startup class in Owin as bellow
[assembly: OwinStartup(typeof(Startup1))]
public class Startup1
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
This is the configuration I use in web.config:
<appSettings>
<add key="owin:appStartup" value="Startup1" />
</appSettings>
In the Global.asax class file, I also add this code:
RouteTable.Routes.MapHubs();
When I fire up the application, this is the error I get:
Error CS0619 'SignalRRouteExtensions.MapHubs(RouteCollection)' is
obsolete: 'Use IAppBuilder.MapSignalR in an Owin Startup class. See
http://go.microsoft.com/fwlink/?LinkId=320578 for more details
if i remember correctly client proxy is camel-cased (generated or dynamic) so you should use
$.connection.hubclass
or add to hub class name attribute
[HubName("Hubclass")]
and also you don't need set signalr routes by RouteTable.Routes.MapHubs owin middleware will handle routing for you...
EDIT: maybe you can check whether your generated proxy was download correctly by signlar/hubs request, check your network tab at your browser. If doesn't, there can be problem with OWIN intialization, maybe you have to set namespace or friendly name at appConfig for proper Startup class detection, check startup detection
<add key="owin:appStartup" value="StartupDemo.ProductionStartup" />

Enable CORS for static resources in ASP .NET MVC?

I've found plenty of resources regarding CORS in Web APIs and for general controllers in ASP .NET MVC.
However, I'm in a situation where I'd like all static resources (CSS and JS files) inside a specific folder to be downloadable through AJAX as well. In other words, enable CORS for those resources or that folder.
How can I accomplish this? I've found no similar question. They are all related to web APIs or general controllers.
Example adapted from Walkthrough: Creating and Registering a Custom HTTP Module. This should add the header to all .js and .css requests.
Create Module
using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
public HelloWorldModule()
{
}
public String ModuleName
{
get { return "HelloWorldModule"; }
}
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".css") || fileExtension.Equals(".js"))
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
}
}
public void Dispose() { }
}
To register the module for IIS 6.0 and IIS 7.0 running in Classic mode
<configuration>
<system.web>
<httpModules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</httpModules>
</system.web>
</configuration>
To register the module for IIS 7.0 running in Integrated mode
<configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</modules>
</system.webServer>
</configuration>
As you are running MVC, make sure you alter the one in the root (not the Views folder).

ASP.NET 3.5 Url Routing Not Working

I am a newbie to asp.net field and having some problem in implementing url routing in asp.net 3.5 (I know it can be easily implemented in asp.net 4.0).
Here is what I have done.....
a) I am using .NET Framework 3.5 SP1.
b) Added System.Web.Routing assembly reference in web.config
<assemblies>
<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
c) Add the UrlRoutingModule HTTP Module
<httpModules>
<add name="RoutingModule"
type="System.Web.Routing.UrlRoutingModule, System.Web.Routing,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
d) Code in Global.asax
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private static void RegisterRoutes()
{
System.Web.Routing.RouteTable.Routes.Add(
"SaveUser", new System.Web.Routing.Route("SaveUser",
new RouteHandler("~/Register.aspx")));
}
e) RouteHandler.cs Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Compilation;
using System.Web.UI;
public class RouteHandler : IRouteHandler
{
public RouteHandler()
{
}
public RouteHandler(string virtualPath)
{
_virtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//var display = BuildManager.CreateInstanceFromVirtualPath(
// _virtualPath, typeof(Page)) as IDisplay;
var abc = BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(Page)) as IDisplay;
return abc;
}
string _virtualPath;
}
f) Code in Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("~/SaveUser");
}
}
and I am getting the following error
The route handler 'RouteHandler' did not return an IHttpHandler
from its GetHttpHandler() method.
I tried 100 of links but could not make out what is wrong.
If anyone have experience in url routing in asp.net 3.5.....pls help.... I need to implement it very urgently....
Thanks in advance....
System.Web.Routing
only available on .net framework version 4
This is probably too little, too late, but I recently upgraded a .NET 3.5 ASP.NET site to use routing and I see your issue.
The problem is that when you configure the routing module, it creates a 2nd context for the routing module that is completely separate from HttpContext.Current in the ASP.NET page. So, you need to set up your handler so that you can access this other context instance (which happens to be a RequestContext).
public class RouteHandler : IRouteHandler
{
public RouteHandler()
{
}
public RouteHandler(string virtualPath)
{
_virtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//Record the request context of the routing module in HttpContext.Current, so we can use it in pages.
HttpContext.Current.Items("requestContext") = requestContext
return BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(Page)) as IDisplay;
}
string _virtualPath;
}
Now, in the page, you need to access the context from HttpContext.Current.Items.
public partial class _Default : System.Web.UI.Page
{
private readonly RequestContext RequestContext
{
get { return (RequestContext)HttpContext.Current.Items("requestContext"); }
}
protected void Page_Load(object sender, EventArgs e)
{
RequestContext.HttpContext.Response.Redirect("~/SaveUser");
}
}
I've been struggling with this same problem, and here's one thing I've learned. On the page referenced by Rick Schott, it says that what you put in web.config depends on what version of IIS you're deploying to. Use this for IIS 6, or IIS 7 in "classic mode":
<httpModules>
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing,
Version=3.5.0.0,
Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
...but in IIS 7+ "integrated mode", add this instead:
<system.webServer>
<modules>
<remove name="UrlRoutingModule" />
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing,
Version=3.5.0.0,
Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</modules>
</system.webServer>
One important thing I've discovered is that though the latter may be what's correct for your IIS, the former is what works inside Visual Studio 2008. So you may have to deploy a different web.config from the one you develop with.
Another useful fact I've found which isn't well documented is that the path pattern you feed to the Route constructor is app-relative, not host-relative, and it should not start with a leading "/" or "~/". Just start with the first subfolder name, or page name if at app root level.
You have to get all that right just to enable it to invoke your IRouteHandler. Then you can worry about the two-contexts issue, if any. I had no trouble writing to requestContext.HttpContext.Items in the handler class and then reading from Context.Items in the target page.
But since you got the error message "did not return an IHttpHandler from its GetHttpHandler()", it sounds like you've got that working at least on your desktop. So the question then is... why are you casting your page instance as IDisplay instead of as IHttpHandler? That seems like the obvious first thing to change. I tried casting the return as Page and it seems to just want a direct cast to IHttpHandler instead.

Url Rewriting of aspx page.pls give me suggestion

I am new in asp.net. I have iis version 6.0. I want to rewrite url. Actually I'm working on a site. When I used this tag in web.config
<urlrewritingnet
rewriteOnlyVirtualUrls="true"
contextItemsPrefix="QueryString"
defaultPage="default.aspx"
defaultProvider="RegEx"
xmlns="http://www.urlrewriting.net/schemas/config/2006/07" >
<rewrites>
<add name="this-is-a-long-page-name" virtualUrl="^~/this-is-a-long-page-name"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/Default.aspx"
ignoreCase="true" />
</rewrites>
</urlrewritingnet>
When I run it, it shows the error "unrecognized configuration section rewriter".
user ,
you need to implement urlrewritemodule , all the requests comes to the urlrewritemodule.
you can write your logic there
public class UrlModule : IHttpModule
{
public virtual void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(this.BaseUrlModule_BeginRequest);
}
public virtual void Dispose()
{
}
protected virtual void BaseUrlModule_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
Rewritethepath(application.Request.Path, application);
}
private void Rewritethepath(string requestedPath, HttpApplication application)
{
application.Context.RewritePath("/yournewurl", String.Empty, QueryString);
}
}
make this entry in your web.config
<httpModules>
<add type="namespace.UrlModule, namespace" name="UrlModule"/>
</httpModules>
Register your httpmodule in your web.config , once everyrequest comes to this you can rewrite the url however you want ,
i recently implemented this and let me know if you need any help, I will defiently help you.
My response doesn't directly answer your question (which is about the UrlRewritingNet library). Instead, I suggest considering Microsoft's official IIS URL Rewrite library, which requires IIS 7.x or IIS Express. The UrlRewritingNet library, though useful a couple years ago, is now a less than ideal way to go about rewriting URLs in IIS/ASP.NET. I offer this suggestion since you mentioned you are new to ASP.NET. :)

Relationship between SVC files and WCF projects?

When creating a WCF project, the default member files are just ordinary csharp class files, rather than svc files. Are svc files required with a WCF project? When should they be used?
.svc files are used when you host your WCF service in IIS.
See Microsoft's doc here and here.
There's a module within IIS that handles the .svc file. Actually, it is the ASPNET ISAPI Module, which hands off the request for the .svc file to one of the handler factory types that has been configured for ASPNET, in this case
System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
If you are hosting your WCF service in something other than IIS, then you don't need the .svc file.
If you are using .net 4.0 or later, you can now "simulate" the .svc via config with the following:
<system.serviceModel>
<!-- bindings, endpoints, behaviors -->
<serviceHostingEnvironment >
<serviceActivations>
<add relativeAddress="MyService.svc" service="MyAssembly.MyService"/>
</serviceActivations>
</serviceHostingEnvironment>
</system.serviceModel>
Then you don't need a physical .svc file nor a global.asax
It is possible to create a WCF project and host it in IIS without using a .svc file.
Instead of implementing your DataContract in your svc code-behind, you implement it in a normal .cs file (i.e. no code behind.)
So, you would have a MyService.cs like this:
public class MyService: IMyService //IMyService defines the contract
{
[WebGet(UriTemplate = "resource/{externalResourceId}")]
public Resource GetResource(string externalResourceId)
{
int resourceId = 0;
if (!Int32.TryParse(externalResourceId, out resourceId) || externalResourceId == 0) // No ID or 0 provided
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
return null;
}
var resource = GetResource(resourceId);
return resource;
}
}
Then comes the thing making this possible. Now you need to create a Global.asax with code-behind where you add an Application_Start event hook:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Edit the base address of MyService by replacing the "MyService" string below
RouteTable.Routes.Add(new ServiceRoute("MyService", new WebServiceHostFactory(), typeof(MyService)));
}
}
One nice thing about this is that you don't have to handle the .svc in your resource URLs. One not so nice thing is that you now have a Global.asax file.

Categories