Authentication failed error when calling web method using $.ajax - c#

When I make a JQuery call, I get an Authentication failed response:
{
Message: "Authentication failed.",
StackTrace: null,
ExceptionType: "System.InvalidOperationException"
}
jQuery call:
$(document).ready(function () {
//Handle the change event for the drop down list
$("#ddRegions").change(function () {
//create the ajax request
$.ajax({
type: "POST", //HTTP method
url: '<%= ResolveUrl("WebForm2.aspx/getLocations")%>', //page/method name
data: "{}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
alert(msg.toSource());
}
});
});
});
The web method:
public static string getLocations() {
System.Diagnostics.Debug.WriteLine("Getting Locations.");
return "{region:auckland, city:auckland}";
}
I added the following to my web.config:
<authorization>
<allow users="*" />
</authorization>
<authentication mode="None" />
And I tried setting the AutoRedirectMode to Off in RouteConfig.cs. This stops the error, but still the web method never gets called. Any suggestions?

Resolved by setting AutoDirectMode to Off in App_Start/RouteConfig.cs
settings.AutoRedirectMode = RedirectMode.Off;
and adding a ScriptManager to the aspx page that has an EnablePageMethods set to 'true':
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>

Related

AJAX Post Test Method Failed to load resource

I created a test web application that is calling my MVC application. I can call the POST fine with Postman and wanted to try and call it from a web browser but I am getting a 405 error. ANy help would be great.
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Test HTML Project
$.ajax({
type: "POST",
url: "URL",
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain: true,
success: function (response) {
console.log('message: ' + "success" + JSON.stringify(json));
},
failure: function (error) {
console.log('message Error' + JSON.stringify(error));
}
});
MVC Application
public class PublicController : ApiController
{
[System.Web.Http.HttpPost]
public IHttpActionResult MethodTest(string key, string action)
{
}
}
web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
you have to fix your ajax.remove headers and contenttype and fix dataType and add data
$.ajax({
type: "POST",
url: "http://localhost:60876/WebApi/public/SkipAuthenticationAndLogin"
data:{
key:"key",
userName:"name",
succesUrl:"url"
},
dataType: "json",
success: function (response) {
console.log('message: ' + "success" + JSON.stringify(response));
},
failure: function (error) {
console.log('message Error' + JSON.stringify(error));
}
});
and remove post from action
public IHttpActionResult MethodTest(string key, string userName, string successUrl)
{
}

I am using Window.onpopstate method in ajax for SPA

I am using Window.onpopstate method in ajax for SPA, before that I used window.history but I got an error like
"jquery-1.10.2.js:8720 Failed to load location:
http://localhost:22102/Coach/AddCoaches, state:
{"url":"/Coach/AddCoaches"}: Cross origin requests are only supported
for protocol schemes: http, data, chrome, chrome-extension, https."
my ajax call is
<script>
$('#loadingImage').hide();
$('.jq-navigation-link').click(function () {
var url = $(this).data('url');
loadPartial(url)
})
function loadPartial(url)
{
$('#renderPartial').html("");
$('#loadingImage').show();
$.ajax({
url: url + "?ispartial=" + true,
type: "GET",
success: function (data) {
$('#loadingImage').hide();
$('#renderPartial').html(data);
}
})
window.history.pushState({ url: url }, '', url);
}
window.onpopstate = function (event) {
debugger
if (event.state) {
var url = "location: " + document.location + ", state: " + JSON.stringify(event.state);
load(url);
}
};
</script>
<script type="text/javascript">
$('body').delegate(".btnUrl", "click", function (e) {
e.preventDefault();
var url = $('.btnUrl').data('url');
//var test = $('.form').serialize();
$('#loadingImage').show();
$.ajax({
async: true,
url: url,
type: 'POST',
data: $('.form').serialize(),
dataType: "json",
success: function (data) {
if (data.Success) {
$('#loadingImage').hide();
loadPartial(data.Url);
}
else {
$('#loadingImage').hide();
loadPartial(data.Url);
}
}
})
})
function load(url) {
$('#renderPartial').html("");
$('#loadingImage').show();
$.ajax({
url: url,
type: "GET",
success: function (data) {
$('#loadingImage').hide();
$('#renderPartial').html(data);
}
})
}
</script>
Error clearly says it is Cross origin requests. Your Web application is using port 8720 and you web API is using port 22102. Browser is considering requests as different origin and for security reason is blocking data for another site request.
For resolving this, you need to enable CORS on your application OR need to host Web application & Web API at same port or same IIS application.
For Enabling cors try:
install nuget package:
Install-Package Microsoft.AspNet.WebApi.Cors
In App_Start/WebApiConfig.cs, add following code in Register method before map routing :
config.EnableCors();
In API Controller, [EnableCors] attribute to the class:
[EnableCors(origins: "http://yoursitehere", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
OR
Adding the header through web.config
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
For more details refer:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
https://forums.asp.net/post/5795304.aspx

Error 500 using C# WebMethod from jQuery ajax

I keep getting error 500 from my ajax function when trying to call WebMethod.
$.ajax({
type: "POST",
url: "BookingCalendar.aspx/TestFunction",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function () {
alert("Error");
}
});
[WebMethod]
public static string TestFunction()
{
return DateTime.Now.ToString();
}
After more looking I found out that GET and POST are disabled by default in .NET. I added this to the web.config file:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
For more information look here.

calling webservice from javascript function and storing the result

This question is with reference to my another question Auto complete not working.
That problem is still there in my code but I thought of doing this other way. I am thinking of calling my webservice from another javascript function and pass the value returned from the service to this autocomplete function as when I try to pass some dummy values to this jquery function its running fine. i am not sure y its is not calling my webservice.
Though now i have written another function to call my service and get the request -
function SendRequest()
{
debugger;
SearchIssues.GetServerResponse(document.getElementById('ctl00_ContentPlaceHolder1_txtIssueNo').value, OnComplete, OnError, OnTimeOut);
}
function OnComplete(arg)
{
alert(arg);
}
function OnTimeOut(arg)
{
alert("timeOut has occured");
}
function OnError(arg)
{
alert("error has occured: " + arg._message);
}
In the script manager tage I have added the reference of my webservice -
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/SearchIssues.asmx" />
</Services>
</asp:ScriptManager>
I have updated my autocomplete function as -
$(function() {
debugger;
$(".tb").autocomplete({
source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] });});
Here I have passed dummy data in source which is working fine.
the signature of my webservice is as -
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetCompletionList(string prefixText)
{....
}
But its still not calling my webservice and is returning some javascript error as -
SearchIssues is undefined
Please Help
Thanks
this worked for me
[WebMethod]
public static Array GetCompletionList(string code)
{
.....your code
}
$.ajax({
type: "POST",
url: "CompletionList.aspx/GetCompletionList",
data: '{"code1":"' +code1 + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (c2) {
....your code
});
});
1> I think while calling you should have full namespace
NameSpace.SearchIssues.GetServerResponse(document.getElementById('ctl00_ContentPlaceHolder1_txtIssueNo').value, OnComplete, OnError, OnTimeOut)
2> Your service class must have [ScriptService] attribute.
3> Test your relative URL for the service
"~/SearchIssues.asmx"

using ajax in asp.net c#

how can i use ajax to call a server side method i tried this code but it gives me the alert error messsage and i can't find my problem please help and thank you :
enter code here
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ImageEditor_UserControl.ascx.cs" Inherits="ImageEditor_UserControl" %>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=uploadButton.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: "ImageEditor_UserControl.ascx/helo",
data: "{}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function () { alert("success"); },
error: function () { alert("error"); }
})
return false;
});
});
</script>
<asp:Button ID="uploadButton" runat="server" Text="Upload" />
C# Code
[WebMethod]
public static string helo() {
return "Message from server.";
}
You should call *.asmx files (there are other options but this is for the beginning).
Look out for tutorials on web services & ajax consuming.
Have you checked on the line $('#<%=uploadButton.ClientID %>').click(function () { that the
<%=uploadButton.ClientID %> is actually replace by the value and not taken literally?
Do you use firefox? if yes, install the addon "FireBug". Enable firebug to check the request and the response.
Firebug will show you sometimes the error message returned from the server, as in you jquery syntax you are not loading the attributes for the method anonymous method callback for error.
error: function (req,error) { alert("error: " + req.statusText); }
This will give you a heads up on what is going wrong.
Unfortunately you cannot call a page method (server side method) that is a part of a user control. You will have to use a method in an aspx page.

Categories