Enable CORS for static resources in ASP .NET MVC? - c#

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).

Related

Can httpModule "capture" outgoing http requests from a web API hosted on IIS?

I have created a class library test project that has one class which implements the IhttpModule interface.
I have a demo web api project that is hosted on my local IIS and has an HttpPost method which inside uses a class that makes outgoing Http requests at third parties.
As of now it works like a charm for the incoming requests but i want to catch every request that comes and goes from my API. I do not care about the responses.
I have already checked the requests made at the third parties and they are correct.
API's web.config :
<system.webServer>
<modules>
<add name="MyIISModule" type="IisTestProject.MyIISModule" />
</modules>
</system.webServer>
MyIISModule.cs :
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(OnBeginRequest);
}
private void OnBeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication) sender;
File.AppendAllLines("C:\\requestHeaders.txt", new List<string>() {$"{DateTime.Now.ToOADate()}_{app.Context.Request.ToString()}" });
}
public void Dispose()
{
}
I made this so i can just check whenever a request happens.
Is there any way to do this without changing my API's code and using only my HttpModule?
Also i have found this:
HTTP modules can only see requests going through IIS/ASP.NET pipeline, while such outbound requests go through Windows sockets directly, and not through IIS/ASP.NET pipeline.
Is there any way to circumvent this?

ASP .Net MapRequestHandler slow

We have rolled out a classic ASP.Net WebService application with large traffic. Though our database is running quite well (<10 ms response times), most of the time spent in WebServer is in the MapRequestHandler stage.
The issue seems to be deep in the ASP .Net stack and without any information available on net, I am clueless as to how to go about improving it.
We use XML payloads for request/response (if that would help in providing a solution).
Please post you handler code and your config files.
MapRequestHandler - The MapRequestHandler event is used by the ASP.NET infrastructure to determine
request handler for the current request based on the file-name extension of the requested resource. MapRequestHandler is an event that the handlers need to implement, I suspect its stuck at some delegate that maps some custom file.
I suspect its 1) Not finding, looping around to find that custom file handler, you may not 2) using the async handler
You have to chase down the various delegate that use this event and setup a break point
Make sure they are Async & Registered for e.g.
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory" />
Then under the handlers verify
<httpHandlers>
<add verb="*" path="*.MyCustomaspx" type="MyCustomHTTPhandler"/>
</httpHandlers>
In your implementation use the async version base handler
// dervie from Async HttpTaskAsyncHandler
public class MyCustomHTTPhandler: HttpTaskAsyncHandler {
public override Task ProcessRequestAsync(HttpContext context)
{
//throw new NotImplementedException();
//blah blah.. some code
}
}
Last resort, not recommended - from SO here, if your handler/page doesnt modify session variables, you can skip the session lock.
<% #Page EnableSessionState="ReadOnly" %>
If your page does not read any session variables, you can opt out of this lock entirely, for that page.
<% #Page EnableSessionState="False" %>
If none of your pages use session variables, just turn off session state in the web.config.
<sessionState mode="Off" />
Based on this if you want to customize session state just based on your specific page/handler
using System;
using System.Web;
public class CustomSessionStateModule : IHttpModule
{
public void Dispose(){ //.. }
public void Init(HttpApplication context){
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e){
HttpContext currentContext = (sender as HttpApplication).Context;
// here you can filter and turn off/on the session state
if (!currentContext.Request.Url.ToString().Contains("My Custom Handler or Page Value")){
// for e.g. change it to read only
currentContext.SetSessionStateBehavior(
System.Web.SessionState.SessionStateBehavior.ReadOnly);
}
else {
//set it back to default
currentContext.SetSessionStateBehavior(
System.Web.SessionState.SessionStateBehavior.Default);
}
}
}

Implement autofac in asp.net web form

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

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