Error when calling ASP.NET web services from Javascript - asp.net

I'm trying to call a ASP.NET web service from Javascript, and it won't recognize the Web Method, even when I fully qualify the name, I'm trying to figure out what is wrong.
Here is the part of my web.config file:
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
Here is my web service declarations
[WebService(Namespace = "http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class SavingService : System.Web.Services.WebService
{
[WebMethod]
public static void SaveToDB(string runCode, string container,
string productType, string inspector, string[][] scoregrid, string notes)
and here is the javascript (QCApp4 is my project's namespace):
function PrepToSave()
{
....
QCApp4.SavingService.SaveToDB(codev, containerv, prodtype, inspector, scoregrid, notes);
}
scoregrid is declared on the js side as a jagged 2d array using the Array() command. That was the only worry I had with regard to the parameters of the web service.
And here is the service reference:
<asp:ScriptManager id="scriptmng" runat="server">
<Services>
<asp:ServiceReference Path="~/SavingService.asmx" />
</Services>
</asp:ScriptManager>
I get errors whether I call the web method directly, or call it like SavingService.SaveToDB, or with the full Qualifiers. The error I get says that SaveToDB is not defined. SavingService is not defined, QCApp4 is not defined, depending on what the first part of the qualified name is entered as.
Am I missing something? Is there something I've set incorrectly?
It turns out I had made my WebMethod static, of course now I'm getting an error in the error console of:
Error: [Exception... "'Sys.Net.WebServiceFailedException: Sys.Net.WebServiceFailedException: The server method 'SaveToDB' failed with the following error: System.NullReferenceException-- Object reference not set to an instance of an object.' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "" data: no]

If you set the InlineScript attribute on the ServiceReference element, it'll write out the JavaScript methods inline with the HTML so you can see exactly what you need to call or if you're calling the wrong thing:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/SavingService.asmx" InlineScript="true" />
</Services>
</asp:ScriptManager>

I screwed up two things with this. I went back and found the video I had previously watched on setting these web services up.
I realized, I had accidentally made the web method static, and also forgotten to add the callback method parameters. Once I added a on complete and an on error handler, it worked fine, no errors in the Error Console.

Related

SharePoint 2013, custom IHttpModule NullReferenceException

Update: Problem solved. Read on.
Any idea why it's apparently not possible anymore to add custom IHttpModules?
My question is related to: HttpModule.Init - safely add HttpApplication.BeginRequest handler in IIS7 integrated mode
However this question is rather old, unanswered and has no SharePoint context. I CAN add my HttpModule to any standard ASP.NET WebForms page.
SharePoint is being hosted in IIS 8. AppPool runs in Integrated Mode. Framework level is 4.0+.
namespace My.Namespace
{
using System;
using System.Web;
public class CustomHttpModule : IHttpModule
{
private static readonly object mutex = new object();
private static bool _isInitialized;
public void Init(HttpApplication context)
{
if (!_isInitialized)
{
lock (mutex)
{
if (_isInitialized) return;
context.BeginRequest += BeginRequest;
_isInitialized = true;
}
}
}
private void BeginRequest(object sender, EventArgs e)
{
}
public void Dispose()
{
}
}
}
Result:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.PipelineModuleStepContainer.GetEventCount(RequestNotification notification, Boolean isPostEvent) +30
System.Web.PipelineStepManager.ResumeSteps(Exception error) +1098
System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) +135
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +604
The web.config looks as follows:
<system.webServer>
<!-- further elements omitted -->
<modules runAllManagedModulesForAllRequests="true">
<remove name="AnonymousIdentification" />
<remove name="FileAuthorization" />
<remove name="Profile" />
<remove name="WebDAVModule" />
<remove name="Session" />
<add name="SPNativeRequestModule" preCondition="integratedMode" />
<add name="SPRequestModule" preCondition="integratedMode" type="Microsoft.SharePoint.ApplicationRuntime.SPRequestModule, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="SharePoint14Module" preCondition="integratedMode" />
<add name="StateServiceModule" type="Microsoft.Office.Server.Administration.StateModule, Microsoft.Office.Server, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="PublishingHttpModule" type="Microsoft.SharePoint.Publishing.PublishingHttpModule, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="DesignHttpModule" preCondition="integratedMode" type="Microsoft.SharePoint.Publishing.Design.DesignHttpModule, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="FederatedAuthentication" type="Microsoft.SharePoint.IdentityModel.SPFederationAuthenticationModule, Microsoft.SharePoint.IdentityModel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="SessionAuthentication" type="Microsoft.SharePoint.IdentityModel.SPSessionAuthenticationModule, Microsoft.SharePoint.IdentityModel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="SPWindowsClaimsAuthentication" type="Microsoft.SharePoint.IdentityModel.SPWindowsClaimsAuthenticationHttpModule, Microsoft.SharePoint.IdentityModel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="SPApplicationAuthentication" type="Microsoft.SharePoint.IdentityModel.SPApplicationAuthenticationModule, Microsoft.SharePoint.IdentityModel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
<add name="CustomModule" type="My.Namespace.CustomHttpModule, My.Namespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=066b2229567b6747" />
</modules>
<!-- further elements omitted -->
</system.webServer>
As soon as I don't attach to the BeginRequest event anymore the page works again. But obviously my http module is rendered useless.
Edit 2013.09.19: Init() is being called twice upon application start. If I attach my event only on the second call the application works but the event doesn't fire.
Edit 2013.09.20: Problem presumably solved. The fact that my Init() method is triggered twice (and no Dispose() is called in between) led me to the assumption there might actually be two co-existing instances of my IHttpModule. And while my previous observation showed that the second instance can have the event attached (not firing, but no negative impact on the application as well) - it apparently is not true vice versa (which is the case with my static _isInitialized "lock").
**So both instances of the IHttpModule need to have the same "configuration" (eventhandlers attached). It is totally normal to have more than one HttpApplication instance running. That's something ASP.NET (or IIS) does internally for optimization purposes. That's the key thing to remember :)
Problem solved. Edited question. See Edit 2013.09.20.

ASP.NET Ajax client-side framework failed to load. when put the ScriptManager on a blank page

I have an error Microsoft JScript runtime error: ASP.NET Ajax client-side framework failed to load. on a blank page using masterpage
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="True">
</asp:ScriptManager>
</form>
</body>
</html>
This is what it render it the end
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form method="post" action="WebForm2.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjE2OTgwNTY5ZGTfWA/dEX85PXBlbkKsVxeLKyIn+mJQ9piW5cbeNE+qww==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="http://ajax.microsoft.com/ajax/4.0/2/WebForms.js" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=6x_aX-LOcgUU-O_K6nM7ST5ViC_naT1e4_j-CY35ASRLpcKYpiapwTARuePHvx3llP-Xhl_AG_ubpM1BzkM5iyn9ThB3m7lmXKvkck0cxTcYiT-VbeKgamKxp9EwxBUyIQN6sSCU9SQm3tMtmzQWRg2&t=ffffffffbad362a4" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/ScriptResource.axd?d=khKEuZ4oUqBYvQxJ1ISpPVIW8_AWWc907q5_v74DI2ruWKTJpldq2osxPkAZ__hffe1Q6HTQUyTbL3Q1mD6MX7V65O5ibxKwb4NvN6ycdZ8vEJ-bz51MO-8uoaP2xioK6npm5n8vldI1d0sOCnH6yw2&t=ffffffffbad362a4" type="text/javascript"></script>
<div>
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1', 'form1', [], [], [], 90, '');
//]]>
</script>
</form>
</body>
</html>
The problems might be that i used to have AjaxControlToolkit in my project but later i use jquery instead. so somewhere in the project might try to add Ajaxcontroltoolkit which i can't find it. i don't know how to fix this error. i have tried to add bin file of ajaxcontroltoolkit back but it seems to not work.
this solution works for me:
The error on client was:
SCRIPT5022: ASP.NET Ajax client-side framework failed to load.
SCRIPT5009: 'Sys' is undefined
After many time to mining the websites, and more solutions, i solve the problem:
the solution for .NET 4.0 is:
Set EnableCdn property of script manager to true, Like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true">
Next Solution and Better Solution is:
add this handler to your web.config
<system.webServer>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
Sys undefined means that you're not getting the client side files loaded on your browser.
Solution 1:
<add verb="GET"
path="ScriptResource.axd"
type="Microsoft.Web.Handlers.ScriptResourceHandler"
validate="false"/>
Solution 2: If you don't have this, add this too under <assemblies>
<add assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Solution3: If that doesn't work too, try deleting files from your "bin" folder and rebuild the solution and clear the cache of your browser.
Solution 4: Add this to your web.config
<location path="ScriptResource.axd">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
for telerik web resources use this code:
<location path="Telerik.Web.UI.WebResource.axd">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
I had enabled WebForms Routing and forgot to add the exception for resources:
routes.Ignore("{resource}.axd/{*pathInfo}");
Another possible cause is script combining/compression in IE 8 & 9. In web.config at the top level (within Configuration), put
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>
On your ToolKitScriptManager put CombineScripts=False, e.g.
<asp:ToolkitScriptManager runat="server" CombineScripts="False">
</asp:ToolkitScriptManager>
see http://robmzd.blogspot.com/2010/02/invalid-character-error.html which is where I figured out the problem
Add EnableScriptCombine="False" to your RadScriptManager as follows:
<telerik:RadScriptManager ID="RadScriptManager1" EnableScriptCombine="False" runat="server" />
I had this problem when I moved my forms to a new server. I spent hours to find the solution.
The problem was that the new server has ASP.NET 4.0 and my web.config was ASP.NET 3.5. So I made a new web.config and everything is ok now.
Simply add the <handlers> section as shown below in your web.config within <system.webServer> and this will fix the problem in no time.
<system.webServer>
.
.
.
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
For me it was the problem with Global.asax code,
Just check below condition before validating session in Application_PreRequestHandlerExecute
Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "SCRIPTRESOURCE.AXD"
Functional code is shown below,
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
if ((Request.Path != Constants.DebugLoginUrl) &&
(Request.Path != Constants.SessionTimeOut) &&
(Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "TRACE.AXD") &&
(Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "SCRIPTRESOURCE.AXD"))
{
// to prevent check of HTTP HANDLER FLUSH - Session State is Invalid
if (HttpContext.Current.Session != null)
{
if (Session[Constants.personId] == null)
{
//your code
}
else
{
Response.Redirect(Constants.SessionTimeOut);
}
}
}
In my case the Ajax loading error occurred only if I reloaded the page, not when the page was loaded for the first time.
Looking at the content in the tag in Site.Master, I noticed that only some of the items had Path attribute set. So, I updated MsAjaxBundle to this: and the problem went away. I also had to modify the WebFormsBundle the same way and now reloading the page works.
What worked for me was to download ASP.NET Ajax from Microsoft.
You might also need to explicitly browse for the correct dll version when you add reference e.g.
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.Web.Extensions.dll
I set Application Pool as ASP.NET 4.0 Classic during installation.
well i just changed RadScriptManger to Simple asp:ScriptManager and it works
Before:
<telerik:RadScriptManager ID="RadScriptManager1" EnableCdn="true" runat="server" />
After
<asp:ScriptManager ID="scrReg" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
Hope it helps
And here's another cause. I installed MySQL Connector/net 6.9.5. Later I started getting the dreaded 'sys undefined' for everything in some, but not all, projects in IE. Many, many hours later I tried Chrome and Opera and the first page opened fine but on post back all the session variables had vanished. That's when the penny finally dropped - Connector/net must have set itself up the session state provider but I had nothing for session state in web.config for the failing projects. Sessionstate inproc fixed it immediately. At least I think that's what happened...
In my case, I had ended up with the mentioned handlers in <httpHandlers> as well as in <handlers>.
Removing the <httpHandlers> section fixed it.
After adding System.Web.MVC reference to my ASP.NET and added default route in global.asax
i.e.
RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "new", action = "Index", id = "" });
}
Started getting the error
Added below line to global.asax.cs to resolve it
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
For anyone working with the Visual Studio 2015 ASP.NET 4.5 WebForms Web Application project template which bundles the ASP.NET AJAX scripts:
https://stackoverflow.com/a/47673606/313935
for me web config was correct.
if web config is correct then.
check your IIS App pool settings in my case App pool pipeline was selected as the classic I made pipeline integrated and it started working.
Go to iis -> rightclick on your application pool -> advance settings ->
Managed Pipelined Mode -> "integrated" -> ok
I am using Visual Studio 2015 ASP.NET 4.5 Web Forms Web Application project and apparently a bad route in an API Controller will also cause this error. I fixed the route and the error went away.
It certainly would be nice for a more descriptive error message as to why the client framework won't load. I spent hours checking web.config settings, clearing the .net temporary directories, checking global.ascx, etc.. The strange thing is while IE 11 died while loading default.aspx, chrome was able to load default.aspx and the web site.
Try changing on the web.config the compilation to false:
<compilation debug="false" targetFramework="4.5">
If none of these answers work for you then you might be in my situation.
Ok, so for me the issue was caused by the ssl certificate expiring today, so after I renewed it then these errors went away.

WSFederationAuthenticationModule.RedirectingToIdentityProvider event is not called

I have 2 events in my Global.asax.cs file
WSFederationAuthenticationModule_SecurityTokenValidated and WSFederationAuthenticationModule_RedirectingToIdentityProvider
WSFederationAuthenticationModule_RedirectingToIdentityProvider is not called by wif engine. Why?
public class MvcApplication : System.Web.HttpApplication
{
void WSFederationAuthenticationModule_SecurityTokenValidated(object sender, SecurityTokenValidatedEventArgs e)
{
FederatedAuthentication.SessionAuthenticationModule.IsSessionMode = true;
}
void WSFederationAuthenticationModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
//some code
}
}
This is microsoft.identityModel section in web.config
<microsoft.identityModel>
<service saveBootstrapTokens="true">
<audienceUris mode="Never">
</audienceUris>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="true" issuer="http://localhost/dss.web.sts.tokenbaker/" realm="http://localhost/dss.web.frontend" requireHttps="false" />
<cookieHandler requireSsl="false" />
</federatedAuthentication>
<issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<trustedIssuers>
<add thumbprint="308efdee6453fff68c402e5eceee5b8bb9eaa619" name="servcert" />
</trustedIssuers>
</issuerNameRegistry>
</service>
</microsoft.identityModel>
You are missing following lines in your web.config:
In configSections element:
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
In system.webServer element
<modules>
<remove name="FormsAuthentication" />
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
</modules>
Your audience Uris is empty. You have to specify your web application, so it can consume this functionality. So, add this line :
<audienceUris>
<add value="http://localhost/dss.web.frontend"/>
</audienceUris>
If your problems reamined after this changes, you can implement your custom authentication module derived from WSFederationAuthenticationModule. Something like this :
public class CustomAuthenticationModule : WSFederationAuthenticationModule
{
public CustomAuthenticationModule()
{
base.SecurityTokenReceived += CustomAuthenticationModule_SecurityTokenReceived;
}
public void CustomAuthenticationModule_SecurityTokenReceived(object sender, SecurityTokenReceivedEventArgs e)
{
}
protected override void OnAuthenticateRequest(object sender, EventArgs args)
{
base.OnAuthenticateRequest(sender, args);
}
}
and then just in config change instead of WSFederationAuthenticationModule put CustomAuthenticationModule with appropriate namespace and assembly signature. So you can intercept calls in your delegate.
Hope this is helpful for you.
Rastko
Add the following to your Global.asax.cs:
void Application_Start()
{
FederatedAuthentication.ServiceConfigurationCreated += OnServiceConfigurationCreated;
}
void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e)
{
FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider += WSFederationAuthenticationModule_RedirectingToIdentityProvider;
}
Credit to https://stackoverflow.com/a/9207505/13932
Make sure you're referencing WSFederationAuthenticationModule from the new namespaceSystem.IdentityModel.Services.
In my case I was still referencing it from the old Microsoft.IdentityModel.Web namespace after migrating the solution to .NET 4.5.
Found my answer here.
It sounds like you may be missing the WSFederationAuthenticationModule in your configuration. Make sure you have this in system.webServer\modules:
<add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
And this in system.web\httpModules:
<add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
Read here for more information.
One thing to check is that you are referencing a consistent assembly between your web.config module and your Global.asax.cs using statement. Since the type RedirectingToIdentityProviderEventArgs exists in both System.IdentityModel.Services and Microsoft.IdentityModel.Web (as of .NET 4.5) you might be adding the module from one assembly in web.config but referencing the event arg from the other assembly in Global.asax.cs. I think that would fail.
My problem was that I had the following modules added to both the system.web/httpModules and system.webServer/modules sections.
<add name="WsFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
Removing the elements from the system.web/httpModules section solved the issue and all events attached to the WSFederationAuthenticationModule instance were being fired.
For the people who are sub-classing WSFederationAuthenticationModule and therefor changing the module registration name in the web.config and are using the auto wiring approach (inside the global.asax.cs) you will also have need to change the beginning of the method name.
For example if you have the following in system.webServer\modules
<add name="CustomWsFedModule" type="SomeLib.CustomWSFederationAuthenticationModule" preCondition="managedHandler" />
You will need the following inside your global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
void CustomWsFedModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
//some code
}
}

JQuery to asmx fails on Windows 2008 R2 SP1

Since the installation of SP1 we are facing problems in calling asmx pages from JQuery client code.
IIS is pointing the JQuery post call to his default 404 page.
We did a roleback of our environment to assert this issue is caused by SP1 and tests confirm it.
Waiting for a fix #MS
Technologies used:
ASP.Net 4.0 -
JQuery -
IIS 7.5 -
Windows 2008 R2 SP1
--Bart
Code Sample calling (front-end):
// Code to load vars...
$.ajax({
type: "POST",
url: "/Handlers/ProductRating.asmx/RateProduct",
data: "{'uniqueId':'" + uniqueId + "','productId':'" + productId + "','points':" + points.toString() + ",'showOwnScore':" + showOwnScore.toString() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert('success');
},
failure: function(msg) {
alert('something went wrong');
}
});
}
Code back-end:
[ScriptService]
public class ProductRating : System.Web.Services.WebService
{
[WebMethod(EnableSession=true)]
public RateProductResponse RateProduct(Guid uniqueId, Guid productId, int points, bool showOwnScore)
{
//Implementation
}
Snapshot1 : With SP1:
http://img812.imageshack.us/i/capture2r.png/
Snapshot2 : Without SP1:
http://img190.imageshack.us/i/capture1qx.png/
I was able to get this working with the following addition to my web.config
I saw another site that suggested clearing the handlers, but that made everything way worse. With this update, I was able to call my web services once again.
<system.webServer>
<handlers>
<add name="AsmxRoutingHandler" verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</handlers>
</system.webServer>
I had the same problem.
Create a Web.Config file containing the following lines:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.web>
<httpHandlers>
<clear />
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add path="*" verb="GET,HEAD,POST" type="System.Web.DefaultHttpHandler" validate="True" />
</httpHandlers>
</system.web>
</location>
</configuration>
Copy this into the directory(s) where you serve out your affected scripts, and restart your web server.
These lines will override your preferred HttpHandlers and set it to use the default handlers instead.
Good luck!
Judging by your screenshots, that seems an awful lot like a URL rewriting issue. Does your site have any overly-greedy URL rewrite rules at the IIS level that could be 302 redirecting /Handlers/ProductRating.asmx/RateProduct?
If you do have rewrite rules, can you try disabling them temporarily to see if that fixes the ASMX issue?

Error while accessing ASP.net webservice using JQuery - JSONP

Please look at the code below and help me to figure out what am I doing wrong in my web service code. I want to set up an asp.net web service that can be consumed using an JSONP. I am using Jquery at client side to access the site. Even after setting up proper attributes my web service still emits xml due to which the aynch call fails.
Web Service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json, XmlSerializeString=false, UseHttpGet=true)]
public string HelloWorld(int id, string __callback) {
return __callback + "({message: 'Hello World'})";
}
}
Web Service Response:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">test({message: 'Hello World'})</string>
Web.Config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"
validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule"
type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
Javascript
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:54404/jsonp/webservice.asmx/HelloWorld?id=2&__callback=?", //?jsonp=MatchSvcCallback
dataType: "jsonp",
data: {},
//jsonp : "MatchSvcCallback",
success: function(msg) {
alert("Inside success callback function"); // not being called
},
error: function(xhr, msg){
var response = JSON.parse(xhr.responseText);
}
});
The js code works with an handler, but fails for the webservice due to xml response.
I think the problem here is because jQuery doesn't set the Content-Type header in the HTTP request for HTTP GET's when using $.ajax(). It only gets sent if the request type is 'POST'. This seems to be the case for both dataType: "jsonp" and dataType: "json".
I tried your example and watched the request/response exchange in Fiddler and sure enough I don't see Content-Type: application/xml; charset=UTF-8 being sent in the headers for HTTP GET requests. The header does get sent if using HTTP POST. I'm guessing the presence of this header is a cue for the ASP.NET web service plumbing to decide whether to return either a JSON or XML formatted response.
It seems you're not the only one with this problem, see the following article on the on Elegant Code website:
Calling Remote ASP.NET Web Services from JQuery
The solution appears to be one of the following:
Use a HttpModule to inject the Content-Type: application/xml; charset=UTF-8 header into the request stream as described in the article above.
Use a HttpHandler for the endpoint as you explained you were doing prior to using an ASP.NET web service.
Try Rick Strahl's page based approach
in the following article (which
is in effect a HttpHandler anyway): JSONP for cross-site Callbacks.

Resources