I have the following code in my ASP.NET web site that simply displays "Hello World" when a button is clicked:
ASPX File:
$.ajax({
type: "POST",
url: "WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
.CS Code behind File:
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
This works fine whenever it is ran locally on my PC (Launched from Visual Studio Debugger) but when I deploy my website to a live server from my hosting company it does not work.
I use the Chrome Debugging Tools to view the the response in the ajax error function and it shows I get an "Internal Server Error 500"
I'm not sure what is going wrong because it works locally but not on a live server. Is there any Web.Config settings that I have to use??
Yes, you should add to your web.config the following, under <configuration>:
<system.webServer>
<httpErrors errorMode="Detailed" />
<asp scriptErrorSentToBrowser="true"/>
</system.webServer>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
<deployment retail="false" />
</system.web>
There is a runtime error that your code generates, and it doesn't seem to be coming from the code you posted. Adding the above snippet in the right place will help you trace the root cause.
Note that the <deployment retail="false" /> might be unnecessary, it depends if the machine hosting your code has this value set to true in it's machine.config. If so, it will override other customErrors settings in your web.config. Though unlikely, I added it just to be on the safe side.
Related
I am unable to get captcha to work on server. It works fine locally and I get it to return a score without issue.
JavaScript after button is clicked.
(function () {
$('#btnLogin').click(function () {
$.ajax({
type: "POST",
url: "/captcha/lasttry.aspx/CaptchaVerify",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var _response = JSON.parse(response.d);
if (_response.score < 0.5) {
$('#status').text("User is not human being! Score = " + _response.score);
$('#status').removeClass('text-info').addClass('text-danger');
}
else {
$('#status').text("User is human being . Score = " + _response.score);
$('#status').removeClass('text-error').addClass('text-success');
}
},
failure: function (response) {
$('#status').text("Error on Server!");
}
});
});
})();
CodeBehind:
[WebMethod]
public static string CaptchaVerify()
{
//It should only call once
if (response.score == 0)
{
var responseString = RecaptchaVerify(Token);
response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);
}
return JsonConvert.SerializeObject(response);
}
private static string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
private static async Task<string> RecaptchaVerify(string recaptchaToken)
{
//try/catch omitted to try to see error with customErrors off
String url = $"{apiAddress}?secret={recaptchaSecret}&response={recaptchaToken}";
HttpClient httpClient = new HttpClient();
String responseString = httpClient.GetStringAsync(url).Result;
return responseString;
}
When I run it remotely I get the following error (1st image Google console, 2nd Wireshark):
Firewall is open to Google, I have added the site to captcha admin. Keys are correct. they have been checked and re-checked. I am not sure if I am missing something in the web.config, or if there is a setting in IIS manager that I am missing.
You can't troubleshoot your problem just based on these error messages. You can try the following methods to get more detailed error messages:
Run the site directly on the server – depending on the configuration of your site/server, you may be able to see the real error if you load the site from a browser located on the same server. You may need to turn off 'show friendly http errors.'
Temporarily add the following within the appropriate tags in your web.config file:
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" />
</system.web>
</configuration>
After you have added those, load the page again to see if you can get a more detailed error.
Open up IIS Manager and try to open up some of the different features by clicking on the icon. If there is an error in the web.config file and it can’t even parse it, sometimes you will get a helpful error in IIS Manager when you try to open a feature.
Look in Event Viewer. Sometimes you can find the detailed error logged in there, particularly Application Event Viewer.
Setup Failed Request Tracing. This will often give you details on the 500 error. This is especially helpful if it is an intermittent 500 error.
Look through the web log files. This is especially helpful for an intermittent 500 error. You can often parse the log files to see if there is a trend with a specific page that is throwing a 500 error.
In case someone else comes across this problem in the future, it was the WinHTTP proxy on the production server. The following code fixed my issue:
WebProxy proxyObject = new WebProxy("http://proxyserver:80/",true);
WebRequest req = WebRequest.Create("http://www.contoso.com");
req.Proxy = proxyObject;
More info can be found at https://learn.microsoft.com/en-us/dotnet/api/system.net.webproxy?view=net-5.0
I'm trying to call a WCF service from ajax call. This is my ajax call:
$j.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
context: this,
async: false,
url: appServicePath + "Student/GetRolesByUserId",
data: JSON.stringify({ "userId": userId }),
success: this.getRolesByIdResponse,
error: this.getRolesByIdFailure
}
);
when I test my service using Fiddler I'm able to get the roles of the user that I'm passing its value from ajax but when I call the service from my application I get an error: 405 Method Not Allowed.
What am I doing wrong?
According to your description, I think this problem is due to cross-domain, the problem generates an OPTIONS request, So the method is not allowed. If you put the script in the same domain as the webservice, you won't have this problem.
Here is Http 405 method document.
https://www.rfc-editor.org/rfc/rfc7231#section-6.5.5
You now need to turn on cross-domain support for a WCF application hosted on the web server side.
Web.config
<system.webServer>
<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>
</system.webServer>
Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Headers.AllKeys.Contains("Origin")&&Request.HttpMethod=="OPTIONS")
{
Response.End();
}
}
Feel free to contact me if you have any questions.
When consuming a WebService, I got the following error:
Request format is unrecognized for URL unexpectedly ending in /myMethodName
How can this be solved?
Found a solution on this website
All you need is to add the following to your web.config
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
More info from Microsoft
Despite 90% of all the information I found (while trying to find a solution to this error) telling me to add the HttpGet and HttpPost to the configuration, that did not work for me... and didn't make sense to me anyway.
My application is running on lots of servers (30+) and I've never had to add this configuration for any of them. Either the version of the application running under .NET 2.0 or .NET 4.0.
The solution for me was to re-register ASP.NET against IIS.
I used the following command line to achieve this...
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
Make sure you're using right method: Post/Get, right content type and right parameters (data).
$.ajax({
type: "POST",
url: "/ajax.asmx/GetNews",
data: "{Lang:'tr'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) { generateNews(msg); }
})
Superb.
Case 2 - where the same issue can arrise) in my case the problem was due to the following line:
<webServices>
<protocols>
<remove name="Documentation"/>
</protocols>
</webServices>
It works well in server as calls are made directly to the webservice function - however will fail if you run the service directly from .Net in the debug environment and want to test running the function manually.
For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)
In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:
<system.webServer>
<handlers>
<remove name="ScriptHandlerFactory" />
<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" />
</handlers>
</system.webServer>
Why it worked without these lines on one web server and not the other I don't know.
In my case the error happened when i move from my local PC Windows 10 to a dedicated server with Windows 2012.
The solution for was to add to the web.config the following lines
<webServices>
<protocols>
<add name="Documentation"/>
</protocols>
</webServices>
I use following line of code to fix this problem. Write the following code in web.config file
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
I did not have the issue when developing in localhost. However, once I published to a web server, the webservice was returning an empty (blank) result and I was seeing the error in my logs.
I fixed it by setting my ajax contentType to :
"application/json; charset=utf-8"
and using :
JSON.stringify()
on the object I was posting.
var postData = {data: myData};
$.ajax({
type: "POST",
url: "../MyService.asmx/MyMethod",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
dataType: "json"
});
I also got this error with apache mod-mono. It looks like the documentation page for webservice is not implemented yet in linux. But the webservice is working despite this error. You should see it by adding ?WSDL at the end of url, i.e http://localhost/WebService1.asmx?WSDL
In html you have to enclose the call in a a form with a GET with something like
label
You can also use a POST with the action being the location of the web service and input the parameter via an input tag.
There are also SOAP and proxy classes.
In my case i had an overload of function that was causing this Exception, once i changed the name of my second function it ran ok, guess web server doesnot support function overloading
a WebMethod which requires a ContextKey,
[WebMethod]
public string[] GetValues(string prefixText, int count, string contextKey)
when this key is not set, got the exception.
Fixing it by assigning AutoCompleteExtender's key.
ac.ContextKey = "myKey";
In our case the problem was caused by the web service being called using the OPTIONS request method (instead of GET or POST).
We still don't know why the problem suddenly appeared. The web service had been running for 5 years perfectly well over both HTTP and HTTPS. We are the only ones that consume the web service and it is always using POST.
Recently we decided to make the site that host the web service SSL only. We added rewrite rules to the Web.config to convert anything HTTP into HTTPS, deployed, and immediately started getting, on top of the regular GET and POST requests, OPTIONS requests. The OPTIONS requests caused the error discussed on this post.
The rest of the application worked perfectly well. But we kept getting hundreds of error reports due to this problem.
There are several posts (e.g. this one) discussing how to handle the OPTIONS method. We went for handling the OPTIONS request directly in the Global.asax. This made the problem dissapear.
protected void Application_BeginRequest(object sender, EventArgs e)
{
var req = HttpContext.Current.Request;
var resp = HttpContext.Current.Response;
if (req.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
resp.AddHeader("Access-Control-Allow-Methods", "GET, POST");
resp.AddHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, SOAPAction");
resp.AddHeader("Access-Control-Max-Age", "1728000");
resp.End();
}
}
I was getting this error until I added (as shown in the code below) $.holdReady(true) at the beginning of my web service call and $.holdReady(false) after it ends. This is jQuery thing to suspend the ready state of the page so any script within document.ready function would be waiting for this (among other possible but unknown to me things).
<span class="AjaxPlaceHolder"></span>
<script type="text/javascript">
$.holdReady(true);
function GetHTML(source, section){
var divToBeWorkedOn = ".AjaxPlaceHolder";
var webMethod = "../MyService.asmx/MyMethod";
var parameters = "{'source':'" + source + "','section':'" + section + "'}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
xhrFields: {
withCredentials: false
},
crossDomain: true,
success: function(data) {
$.holdReady(false);
var myData = data.d;
if (myData != null) {
$(divToBeWorkedOn).prepend(myData.html);
}
},
error: function(e){
$.holdReady(false);
$(divToBeWorkedOn).html("Unavailable");
}
});
}
GetHTML("external", "Staff Directory");
</script>
Make sure you disable custom errors. This can mask the original problem in your code:
change
<customErrors defaultRedirect="~/Error" mode="On">
to
<customErrors defaultRedirect="~/Error" mode="Off">
I have the exact code when declaring webmethod in aspx file and in asmx file. They are webmethods exposed for client scripting. I just want to use webmethod inside asmx file, but cannot get it to work.
When I reference a method in aspx file everything works just fine, but when I reference webmethod in asmx I receive an error method unknown. I checked all solutions for "unknown method, parametar methodname" but nothing helped.
Webmethod is both declared in a similar way:
[WebMethod]
public static string[] InsertRecord(string param) { return something }
Only difference is that asmx contains [System.Web.Script.Services.ScriptService] for class.
I cant figure out what is the problem.
WebMethod is being called from Jquery script places in a control (ascx).
function InsertRecord(notice)
{
$.ajax({
type: "POST",
url: "/Webservices/Records.asmx/InsertRecord",
data: "{ 'notice':'" + notice + '' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
},
error: function(msg) {}
});
}
your web.config file maybe needs this (check if it is there):
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
you neeed to uset httppost and httpget in your web.config file, or your ajax call will never happen.
When consuming a WebService, I got the following error:
Request format is unrecognized for URL unexpectedly ending in /myMethodName
How can this be solved?
Found a solution on this website
All you need is to add the following to your web.config
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
More info from Microsoft
Despite 90% of all the information I found (while trying to find a solution to this error) telling me to add the HttpGet and HttpPost to the configuration, that did not work for me... and didn't make sense to me anyway.
My application is running on lots of servers (30+) and I've never had to add this configuration for any of them. Either the version of the application running under .NET 2.0 or .NET 4.0.
The solution for me was to re-register ASP.NET against IIS.
I used the following command line to achieve this...
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
Make sure you're using right method: Post/Get, right content type and right parameters (data).
$.ajax({
type: "POST",
url: "/ajax.asmx/GetNews",
data: "{Lang:'tr'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) { generateNews(msg); }
})
Superb.
Case 2 - where the same issue can arrise) in my case the problem was due to the following line:
<webServices>
<protocols>
<remove name="Documentation"/>
</protocols>
</webServices>
It works well in server as calls are made directly to the webservice function - however will fail if you run the service directly from .Net in the debug environment and want to test running the function manually.
For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)
In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:
<system.webServer>
<handlers>
<remove name="ScriptHandlerFactory" />
<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" />
</handlers>
</system.webServer>
Why it worked without these lines on one web server and not the other I don't know.
In my case the error happened when i move from my local PC Windows 10 to a dedicated server with Windows 2012.
The solution for was to add to the web.config the following lines
<webServices>
<protocols>
<add name="Documentation"/>
</protocols>
</webServices>
I use following line of code to fix this problem. Write the following code in web.config file
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
I did not have the issue when developing in localhost. However, once I published to a web server, the webservice was returning an empty (blank) result and I was seeing the error in my logs.
I fixed it by setting my ajax contentType to :
"application/json; charset=utf-8"
and using :
JSON.stringify()
on the object I was posting.
var postData = {data: myData};
$.ajax({
type: "POST",
url: "../MyService.asmx/MyMethod",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
dataType: "json"
});
I also got this error with apache mod-mono. It looks like the documentation page for webservice is not implemented yet in linux. But the webservice is working despite this error. You should see it by adding ?WSDL at the end of url, i.e http://localhost/WebService1.asmx?WSDL
In html you have to enclose the call in a a form with a GET with something like
label
You can also use a POST with the action being the location of the web service and input the parameter via an input tag.
There are also SOAP and proxy classes.
In my case i had an overload of function that was causing this Exception, once i changed the name of my second function it ran ok, guess web server doesnot support function overloading
a WebMethod which requires a ContextKey,
[WebMethod]
public string[] GetValues(string prefixText, int count, string contextKey)
when this key is not set, got the exception.
Fixing it by assigning AutoCompleteExtender's key.
ac.ContextKey = "myKey";
In our case the problem was caused by the web service being called using the OPTIONS request method (instead of GET or POST).
We still don't know why the problem suddenly appeared. The web service had been running for 5 years perfectly well over both HTTP and HTTPS. We are the only ones that consume the web service and it is always using POST.
Recently we decided to make the site that host the web service SSL only. We added rewrite rules to the Web.config to convert anything HTTP into HTTPS, deployed, and immediately started getting, on top of the regular GET and POST requests, OPTIONS requests. The OPTIONS requests caused the error discussed on this post.
The rest of the application worked perfectly well. But we kept getting hundreds of error reports due to this problem.
There are several posts (e.g. this one) discussing how to handle the OPTIONS method. We went for handling the OPTIONS request directly in the Global.asax. This made the problem dissapear.
protected void Application_BeginRequest(object sender, EventArgs e)
{
var req = HttpContext.Current.Request;
var resp = HttpContext.Current.Response;
if (req.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
resp.AddHeader("Access-Control-Allow-Methods", "GET, POST");
resp.AddHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, SOAPAction");
resp.AddHeader("Access-Control-Max-Age", "1728000");
resp.End();
}
}
I was getting this error until I added (as shown in the code below) $.holdReady(true) at the beginning of my web service call and $.holdReady(false) after it ends. This is jQuery thing to suspend the ready state of the page so any script within document.ready function would be waiting for this (among other possible but unknown to me things).
<span class="AjaxPlaceHolder"></span>
<script type="text/javascript">
$.holdReady(true);
function GetHTML(source, section){
var divToBeWorkedOn = ".AjaxPlaceHolder";
var webMethod = "../MyService.asmx/MyMethod";
var parameters = "{'source':'" + source + "','section':'" + section + "'}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
xhrFields: {
withCredentials: false
},
crossDomain: true,
success: function(data) {
$.holdReady(false);
var myData = data.d;
if (myData != null) {
$(divToBeWorkedOn).prepend(myData.html);
}
},
error: function(e){
$.holdReady(false);
$(divToBeWorkedOn).html("Unavailable");
}
});
}
GetHTML("external", "Staff Directory");
</script>
Make sure you disable custom errors. This can mask the original problem in your code:
change
<customErrors defaultRedirect="~/Error" mode="On">
to
<customErrors defaultRedirect="~/Error" mode="Off">