asp.net web api in sitecore - asp.net-mvc-3

I would like to use ASP.Net Web API (http://asp.net/Webapi) in sitecore. I keep getting 404 when i try to browse the API's though i added the
<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="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
in web.config. Referred the necessary assemblies. But, stil cant get through..
I am using web application project. I did few samples in web application project, they work fine. but, integrating with sitecore giving me hard time.
any inputs please..?
thanks

This could be Sitecore being a wise guy and interrupting your requests to try and find the URL in the content tree.
If you know the URLs you are going to be calling (or part of the paths to them) you can add them to the IgnoreUrlPrefixes setting in the config.
See nice little post here:
http://sitecoreblog.alexshyba.com/2011/05/teach-sitecore-to-ignore-directory.html

If you are creating webapi routes, you could also make a step in the RequestPipeline, that aborts the pipeline if it finds a route that matches the current URL
public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args)
{
RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(args.Context));
if (routeData != null)
{
HttpContext.Current.RemapHandler(routeData.RouteHandler.GetHttpHandler(HttpContext.Current.Request.RequestContext));
args.AbortPipeline();
}
}
With that you could set it right after it resolves the database and the site, so you can use Sitecore.Context to handle database access and etc.

Related

asp.net 4 Webform application with custom urlrewrite fails on IIS 8

We had some ASP.NET 3.5 and ASP.NET 4 webform websites with Custom UrlRewrite which programmatically map SEO friendly urls (http://example.com/key/This-is-sample-text-in-url.html) to physical address (http://example.com/key.aspx)
These websites worked perfect in IIS 6 with C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll for 3.5 and c:\windows\microsoft.net\framework\v4.0.30319\aspnet_isapi.dll for 4.0 in application extension mapping window.
after migrating to windows 2012 all 3.5 websites work using classic .NET 3.5 AppPool and this statement in handlers section:
<remove name="ASP.Net-ISAPI-Wildcard" />
<add name="ASP.Net-ISAPI-Wildcard" path="*"
verb="*" type="" modules="IsapiModule"
scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll"
resourceType="Unspecified"
requireAccess="None"
allowPathInfo="false"
preCondition="classicMode,runtimeVersionv2.0,bitness64"
responseBufferLimit="4194304" />
I expected using the same Classic .NET 4.0 AppPool and the following handler should work but didn't:
<remove name="ASP.Net-ISAPI-Wildcard" />
<add name="ASP.Net-ISAPI-Wildcard" path="*"
verb="*" type="" modules="IsapiModule"
scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
resourceType="Unspecified"
requireAccess="None"
allowPathInfo="false"
preCondition="classicMode,runtimeVersionv4.0,bitness64"
responseBufferLimit="4194304" />
I still get HTTP Error 404.0 - Not Found
Module: IIS Web Core
Notification: MapRequestHandler
Handler: StaticFile
Error Code: 0x80070002
I cant downgrade website and couldn't find anything useful to find the source of error. Site log file do not provide any details, no errors in event logs.
I suspected there may be a conflict in handler mappings and tried to disable irrelevant or suspicious entries via Web.Config but there was no change.
I don't know but maybe ASP.Net-ISAPI-Wildcard is not able to catch the request and finally process ends up with StaticFile handler, though in ordered list, ASP.Net-ISAPI-Wildcard is on top and StaticFile is the last.
I appreciate if anybody has a solution to this.
p.s. in the sample above target page works i.e. url to (http://example.com/key.aspx)
Solved
This is in case anybody face the same situation
The handler I added was correct, but only for 64bit applications, so when I added 32 bit version of handler problem solved. As I had set Any Platform in configuration Manager I didn't think this may be a platform matter.
<remove name="ASP.Net-ISAPI-Wildcard" />
<add name="ASP.Net-ISAPI-Wildcard" path="*"
verb="*" type="" modules="IsapiModule"
scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
resourceType="Unspecified"
requireAccess="None"
allowPathInfo="false"
preCondition="classicMode,runtimeVersionv4.0,bitness64"
responseBufferLimit="4194304" />
<remove name="ASP.Net-ISAPI-Wildcard-32" />
<add name="ASP.Net-ISAPI-Wildcard-32" path="*"
verb="*" type="" modules="IsapiModule"
scriptProcessor="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
resourceType="Unspecified"
requireAccess="None"
allowPathInfo="false"
preCondition="classicMode,runtimeVersionv4.0,bitness32"
responseBufferLimit="4194304" />

ASP.NET MVC stops executing actions when runAllManagedModulesForAllRequests=false

When I set runAllManagedModulesForAllRequests=false to increase MVC performance the MVC stops executing Actions like [ActionName("membership.asp")]. I get 404 error on IIS7.5.
Any idea how to solve this?
I have found the solution by myself. Just need to add extension to web.config file which should be handled by MVC.
<system.webServer>
<modules runAllManagedModulesForAllRequests="false" />
<handlers>
<add name="ClassicASP" path="*.asp" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="File" preCondition="integratedMode" />
</handlers>

AngularJS + ASP.NET Web API Cross-Domain Issue

Moving forward with my mobile app development learning process, I've found a new obstacle: Cross-origin Request Sharing or CORS.
I am using a combination of AngularJS + jQuery Mobile (Cordova phone client) and ASP.NET Web API (backend). My issue is that I have not been able to complete a POST request (or any other type of request) to an API controller.
My AngularJS controller uses the $http.post() service method to call the Web API controller. However, Chrome debugger says that the call failed in an OPTIONS request (possibly the CORS preflight request).
I have implemented the CORS action selector from the following post: Enabling CORS in Web API Project. Even tough I can call the api method from Fiddler, AngularJS keeps failing on the OPTIONS preflight request.
Is there anything I should be aware of about AngularJS and cross-domain calls? Any possible solution to my predicament?
Thanks.
You can skip the preflight option request by using content-type : application/x-www-form-urlencoded.
AngularJS:
var user = {
ID: 1,
Name: 'test'
};
$http({
url: "api.localhost/api/users/addUser",
method: "POST",
data: $.param(user),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
withCredentials: true,
}).success(function (data, status, headers, config) {
console.log(data);
})
Web api:
[HttpPost]
public string AddUser(User user)
{
// Do something
return user.Name + " added";
}
Web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<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-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="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
While stumbling onto this issue with AngularJS 1.3 with Microsoft Web API 2 I found a simple solution to the CORS configuration issue.
First from Nuget intall - Microsoft WebApi Cors
Install-Package Microsoft.AspNet.WebApi.Cors
Then in your WebApiConfig.cs file:
var cors = new System.Web.Http.Cors.EnableCorsAttribute("www.my-angular-web-site.com", "*", "*");
config.EnableCors(cors);
You can also enable CORS everywhere with a * instead of your web site but that defeats the purpose of CORS and opens up security holes - but you can do it for testing.
The WebApi.Cors assembly also lets you enable cors controller by controller or with other more granular details. Other details can be found here on the Web API site.
Check out Thinktecture Cors objects, with those (nugettable) you can get full CORS support in WebApi without any code of your own.
Even with a correct CORS implementation I've had a really strange issue with IIS 7 that was solved by enabling all verbs for WebDav (yes, WebDav - don't ask me why I just followed instructions on a blog post :-D).
Do this:
Open IIS manager, go to your application's Handler Mapping.
Double click the WebDav handler
Click "Request Restriction"
On the "Verbs" tab, select "All verbs".
Again, no idea why WebApi uses WebDav, but this solved problems with POST and DELETE that wouldn't work in spite of a correct CORS implementation.
Mostly the developers while running there UI and service on Localhost face this issue - There are many ways in which this can be resolved - alot of the developers tend to fix it at browser level " but thats a security breach.
Correct method is to fix this at your Web Service Layer- Following video will explain and solve this
Watch CORS- Implementing Cross Origin Resource Sharing ("EXPLAINED - Cross Origin Resource Sharing")!

Azure and HttpHandlers

I have a HttpHandler for an asp.net mvc application. I've tested the handler for asp.net and asp.net mvc 3 applications and everything works as expected.
When I use the HttpHandler in an Azure based asp.net mvc 3 application the 'ProcessRequest' method is NOT being called - I can see the HttpHandler being created.
I have the following web.config and this works for a standard asp.net mvc 3 app:
<system.web>
<httpHandlers>
<add type="TestWebRole.Infrastructure.HttpHandlers.EPubHandler"
path="*.epub"
verb="*" />
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<add name="EPubHandler"
type="TestWebRole.Infrastructure.HttpHandlers.EPubHandler"
path="*.epub"
verb="*"
resourceType="Unspecified"
allowPathInfo="false"
modules="IsapiModule"
scriptProcessor="%path%\aspnet_isapi.dll"/>
</handlers>
</system.webServer>
I also have the following statement in the global.asax.cs file to specify ignoring asp.net ,mvc routing for the extension type:
routes.IgnoreRoute("{resource}.epub/{*pathInfo}");
What do I have to configure to get this working when running in Azure - locally or deployed into the cloud?
Just to try, why don't you remove the httpHandlers section under system.web and leave only that in the system.webServer. And also strip all the unnecessary attributes from the one under system.webServer (scriptProcessor, modules, allowPathInfo).
And also you may check for any uncought exception, event log entry, anything showing some kind of error.

Custom Html Helpers in Asp.net MVC Areas

I have some custom Html helpers for my Asp.net MVC 3 app. In the main application they work correctly as I have put the following in my Web.Config:
<pages clientIDMode="AutoID">
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
<add namespace="WebDibaelsaMVC.Utils.HtmlHelpers" />
<add namespace="WebDibaelsaMVC.Utils.HtmlHelpers.DTOs" />
</namespaces>
</pages>
but I have now created an area and to make my custom helpers work I have to add a using in every page where I use them. Is there a way to add the default namespaces for that area?
If you are using Razor you might need to add the reference to the <namespaces> section in the ~/Views/web.config and ~/Areas/YourAreaName/Views/web.config and not the main ~/web.config file. Also make sure you recompile the project, open close the view, maybe even restart Visual Studio for changes to take effect (in terms of Intellisense, it will work if you run the project).

Resources