I need help with wcf service. i have a ajax-enabled wcf service:
public class AddFavorites : Page
{
// Add [WebGet] attribute to use HTTP GET
[WebGet(RequestFormat = WebMessageFormat.Json)]
[OperationContract]
public void AddFavorite()
{
this.AddMyFavorite(10, "sometext", "sometext");
}
}
And clientside looks like this:
function AddFavorite() {
$.ajax({
type: "GET",
url: "/WebServices/AddFavorites.svc/AddFavorite",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
});
};
Im using fiddler to trace the application and i always get HTTP500. The class is inherited from Page class and uses the AddMyFavorite method that takes care of database. Website is hosted on iis7
An HTTP 500 error is something bad that happened on the server. Go in debug mode and debug your service - you'll see a more descriptive message about what went wrong. I would guess that the AddMyFavorite method throws and exception of some kind, but you have to debug this to see for sure.
Is there anything returned in 'Textview' in fiddler? You can see the actual error returned in firebug net panel.
Related
Is it even possible? To call a code-behind c# function from javascript in a visual web part?
It is a complex function so converting all my codes to client side is not an option. I want the logic that is there in this function to happen without a page refresh. This is the background of my issue.
Thanks guys..
You can use jQuery ajax to call server side method and get the response to be used in javascript. This article has simple and good example to show what you need to do.
Code behind
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Javascript
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Why don`t you use a Webservice (Ajax-Enabled WCF Service) which can be called via AJAX?
I think this would be the clean way. Put your logic in an extra class and use this class in the webservice and your webpart. Then you cann call the Method from Code and from Javascript.
In researching this problem most SO issues were about the static method as a fix.
Since it's not working with the real (and a bit sophisticated) WebMethod I've just created a simple one for the sake of checking if reaching the method itself is possible.
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static string HelloWorld()
{
return "Hello World!";
}
The call.
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "usersWebMethods.aspx/HelloWorld",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
});
</script>
It always comes down to 500 (Internal Server Error)
Unknown web method HelloWorld.
Parameter name: methodName
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unknown web method HelloWorld.
Parameter name: methodName
Why is this failing?
I had this issue as well, but slightly differently I had this method in a .asmx file and so ran across the "static" issue, but in a different way.
If you have a method as part of your Page class, it must be static.
If you've put a method in an .asmx file to use across several pages, it must not be static.
I had a problem in the actual .aspx file, the line
<%# Page Language="C#"
AutoEventWireup="true"
CodeBehind="xxx.xxx.cs" Inherits="xxx.xxx" %>
wasn't present in the code. How did it get changed? I Don't know :(.
For me, the primary issues was to change javascript post to pass in no arguments such as
$http.post("Status.aspx/MyData", {})
Then to verify nothing was cached, I then deleted [System.Web.Services.WebMethod] in the code behind file above public static string MyData(). Then I built the project to failure, then re-added the aformentioned deleted attribute and built to success.
Upon running it worked.
Missing the [WebMethod] above your server side function will also cause this error.
To be honest, I've just realised "again" how tired we could be in some cases.
For me it was just a private method instead of a public one.
In my case there was a problem in the URL, it was a Asp.Net Website application:
For ex:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "usersWebMethods.aspx/HelloWorld", <----- Here
dataType: "json",
success: function (data) {
alert(data.d);
}
});
My usersWebMethods.aspx in inside UI (Custom Created) folder so If I put URL as usersWebMethods.aspx/HelloWorld it does not work but when I added leading / to it then ajax method called properly!
Changed from:
usersWebMethods.aspx/HelloWorld
To
/usersWebMethods.aspx/HelloWorld --
I run into this exact problem in ASP.net(framework/web forms) with JS using webservice and I solved it by removing the static key word from the method declaration
[WebMethod]
public List<ViewModel> GetAirLines()
{
//Code goes here
}
instead of
[WebMethod]
public static List<ViewModel> GetAirLines()
{
//Code goes here
}
Recently I was faced with some strange server behavior - it started to return a 500 error at several ajax POST requests. All was working fine before. GET requests work fine. I have made Visual Studio trace my code exceptions but I still cannot see requests coming in while debugging. Do you have any ideas?
Example
$.ajax({
type: "POST",
url: "/home/some-action",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
}
});
[POST("some-action")]
public ActionResult SomeAction()
{
return new JsonNetResult("success request");
}
Update
I use this prefix for my controller:
[RoutePrefix("home")]
So you're using Attribute Routing?
I can't see your Controller but I assume you're missing the Route for /home in the controller, or removed it from [POST("/home/some-action")]
We need more information though. Current assumption is the URL doesn't exist.
I am trying posting a data to a web service. And this service in a different project in same solution.
This project name is WebServices and web service's name is HastaTahlilUyariService.asmx.
My code is here:
$.ajax(
{
type: "POST",
url: "WebServices/HastaTahlilUyariService.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert( 'hata'+ msg);
}
}
);
I think my url is wrong. How can i give correct url.
Thanks in advance...
You might want to change your url to something that isn't relative to where you are right now, such as url: '/WebServices/... (initial slash...)
Using the firebug addon for firefox, you can inspect the AJAX callback and see what exact URL is being requested. You can copy that URL, and you should be able to point your browser to the URL of the asmx (i.e. without the last parameter, which is the method name).
Other than that, you need to make sure you've uncommented the ScriptService attribute in the top few lines of the asmx code file. It is commented out by default, but it needs to be there to allow jQuery to access the webservice.
First of all: build your webservice, and configure it to run under something like http://localhost/services/myservice.asmx in IIS Configuration Manager. Open IIS Manager, rightclick on website -> New Virtual Directory; and navigate to the folder where your webservice is located. Name the virtual directory then services.
Then call the service with it's fully qualified url like http://localhost/myservice.asmx/function.
The most easy way to do what you are trying to do (well, I guess)
Create the method you want to call in your codebehind like
[WebMethod]
public static object MethodToCallFromAjax(string argument)
{
//do something
return result;
}
Then add a ScriptManager to your aspx page; and set enablePageMethods=true. Then call your method from JavaScript like:
PageMethods.MethodToCallFromAjax("argument value", function(msg) { alert(msg); });
edit: removed some stuff about json and asmx that wasn't true :-)
Another option to look into is the standard XMLHttpRequest object that is built into the browser (for IE 6 you have to use the ActiveX object with the same name). It makes calling XML services pretty easy, although you end up having to some of the SOAP formatting yourself.
Wikipedia entry for XMLHttpRequest
I'm trying to use jQuery and JSON with a C# Web Service that I wrote. No matter what, the following code will only output in XML.
Webservice Code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World!";
}
I also have these attributes assigned to the class
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
jQuery Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ScheduleComputerDS.asmx/HelloWorld",
data: "{}",
dataType: "jsonp",
success: function(data) {
alert(data);
}
});
The ASMX page always returns as content type "text/xml". Anything I'm missing?
EDITS: In response to a couple answers:
If I have the datatype as just "json" the content is still XML and jQuery also will not call my callback function. If I add the "&callback=?" to the url, IIS throws a HTTP 500 error.
My class does inherit from "System.Web.Services.WebService".
From doing some research on your guys answers, it looks like I do need to mess with WCF. Unfortunately the JSON that is returned is more designed for MS Ajax and is a lot of useless bloat for my use. I may look into an open source library like Jayrock or something similar.
Thanks for all your help!
I think there's a typo:
dataType: "jsonp",
Should be:
dataType: "json",
As far as I know, the ScriptService attribute just allows the service to automatically create a JavaScript proxy (by appending /js to the endpoint address - ScheduleComputerDS.asmx/js in your case). It does not allow you to call the operations on the service the way you're trying to do.
You could instead use a RESTful WCF service (which requires .NET 3.5) which you can access by sending a properly shaped URI via an HTTP GET.
Rich Strahl has a really basic post that should help you out with this.
http://www.west-wind.com/weblog/posts/164419.aspx
Have you tried with datatype json?
Also, have a look at Encosia's Using jQuery to Consume ASP.NET JSON Web Services article on the matter. There's some good info on common pitfalls too.