using wcf instead of web service ! - c#

I'm using ajax in my website to call some information from a UserControl called NewsFeed.ascx which is found in the folder 'controls', my way is to make a web service page (in a folder called WebMethods) which contain a function in my case called GetRSSReader which returns a string format:
[WebMethod]
public string GetRSSReader()
{
Page page = new Page();
UserControl ctl =
(UserControl)page.LoadControl("~/Controls/NewsFeed.ascx");
page.Controls.Add(ctl);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
then I call this page using Jquery (which I found it too heavy) to get the returned data as a JSON like this :
<div id="Content"></div>
<script type="text/javascript" defer="defer" src="../JAVA/Default.js"></script>
>
$(document).ready(Update);
function Requests()
{
$.ajax({
type: "POST",
url: "../WebMethods/Feed.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#Content').html(msg.d);
}
});
}
the Jquery.js and this page (default.js) founded in the folder Java
my question : can I not to use webService and instead using WCF !!! and how !?

What you refer to as "web services" is the old "ASMX Web Service" feature of .NET (sometimes known as ASP.NET Web Services).
WCF is the replacement for ASMX web services.
See https://stackoverflow.com/tags/wcf/info for some getting-started information.

If you're just returning JSON then I highly recommend you simply use an HttpHandler instead of some combination of WCF, SOAP, UserControls, and whatever else you're throwing in there. Here's a quick tutorial on the subject. You'd save yourself the overhead of page life-cycle stuff that you don't need. And returning the JSON is as simple as serializing your return values with the JavaScriptSerializer.

Related

prevent returned json being wrapped in { d: [duplicate]

I've created a simple C# asp.net web service function which returns a string message
and I am calling it from page using jquery ajax.
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return DateTime.Now.ToString();
}
JS:
$(document).ready(function() {
//alert("ready");
$.ajax({
type: "POST",
contentType: "application/json; chatset=utf-8",
url: "WebService2.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
//alert(msg); //doesnt works
alert(msg.d);
}
});
});
My question is that why does alert(msg); doesnt works
It's a security hardening mechanism.
Essentially, it helps protecting against CSRF type of attacks where the attacker reads a JavaScript array (downloaded as Json) from a victim website. They can do that by overriding JavaScript's Array type. d causes the returned Json to not be an array and thus turns Array overriding useless for the attacker.
See this great blog post: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
ASP.NET and WCF JSON service endpoints actually wrap their JSON in an
object with the “d” property to circumvent a subtle potential
security flaw when using JSON
Phil Haack's post on this: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
This was introduced from ASP.NET3.5. If you want msg to work in both frameworks before and after 3.5, just try this small hack.
var data = msg.hasOwnProperty("d") ? msg.d : msg;
Courtesy Dave Ward: Never worry about ASP.NET AJAX’s .d again

Jquery Ajax call to ASMX web service error

I have a ASP.NET Web Forms application that has an ASMX web service file with a single method at the moment. I am trying to call that method from another file in the same project, but it does not seem to be working. When I look at my console window in chrome it states there is an internal 500 error with the web service. using the ASMX interface I am able to manually invoke the method, but it doesn't invoke from my AJAX code. I have been unable to determine the source of my error.
ASMX Web Method
[WebMethod]
public string TestMethod()
{
string x = "{Name:Shooter McGavin}";
return x;
}
JQuery from ASP.NET Page. I know the click event is firing and I also confirmed that the code is progressing inside the IF statement if the form is valid.
$("#AddSupplierBtn").click(function()
{
if ($("#AddSupplier").valid())
{
$.ajax({
type: "POST",
url: "/StockPileDelivery.asmx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.data);
}
});
}
});

Issue with Url routing - Asp.Net MVC Razor

I use "/Controller/ActionName" url format for my ajax calls. This pattern works fine with my development server that has this pattern
/Controller/ActionName
My application has been deployed to IIS with the following url pattern
/domain/Controller/ActionName
So whenever I call a resource it routes to /Controller/ActionName instead of /domain/Controller/ActionName there by resulting in 404 error. Is there any quick fix for this by modifying the routeconfiguration such that it works on both the devl as well as the IIS.
If you defining the relative urls "manually" as a string try not using a '/' in the beginning.
"Controller/ActionName"
Edit
What I've done the the past is included a Partial Razor View that is responsible of setting urls using #Url.Action()
Partial - Shared/JavascriptUrlsPartial.cshtml
<script type="text/javascript">
(function ($, app) {
app.urls =
{
actionA: '#Url.Action("Controller", "ActionA")',
};
})(jQuery, app = app || {});
</script>
Then you reference the rendered url in javascript.
$.ajax({
url: app.urls.actionA,
//etc
})
This partial is then included in the _Layout.cshtml.
In my Razor view, we have Ajax calls like:
var model = { searchId: searchId, newSearchName: searchName, newSearchDescription: description };
$.ajax({
url: '#Url.Action("Rename", "Search")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
We have not done anything special in local or production environment. We host the application on IIS 7.5.
I could not make out what's different in your case from your question and comments. If this does not solve the problem please add more information around your setup.

Call method in code-behind (secure page) from client (JavaScript)

Let me start of by saying I am very new to ASP.NET and C#.
I have a simple web form containing data which I want to send to a code-behind page.
The idea is to capture the data and send it as a JSON object to a code-behind method.
Note that this is done via JavaScript/AJAX (see code below).
The code-behind method will then do a trivial HTTP "PUT" request to update the data.
The .apsx page is located in the Secure folder (uses a Secure Master).
Don't know if that will affect the method calling?
Following is the code I have thus far.
JavaScript/AJAX:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "PUT",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
Code-behind:
namespace PartyAtVendors.Secure
{
[WebService]
public partial class Profile : System.Web.UI.Page
{
[WebMethod]
public static bool UpdateVendor(PartyAtApi.Models.Vendors vendor)
{
return true;
}
}
}
Update:
Problem is as follows. The codebehind method isn't called. When I run and test the code and use Chrome's "inspect element" I receive the error:
PUT http://localhost:50671/Secure/Profile.aspx/UpdateVendor 404 (Not Found)
Such static methods are called Page Methods in asp.net.
You call them form javascript like this on the same page as follows:
string data = "{mydata:myvalue}";
PageMethods.UpdateVendor(data);
You need to have a ScriptManager on the page and it should have PageMethods enabled
<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>
The page method must be defined on the page. It cannot be defined in a control, master page, or base page.
PageMethods only support HTTP POST(Even when you call them without the javascript proxy of PageMethods). You can read the details of this security limitation in this blog post by Scott Guthrie. Using the PUT verb is causing the 404 error.
ASP.NET AJAX 1.0 by default only allows the HTTP POST verb to be used
when invoking web methods using JSON
Your webmethod & javascript method should be on same page.
Hi managed to sort out what was wrong.
I simply changed the HTTP method to "POST" as follows:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "POST",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
$.ajax(saveOptions);
This seemed to fix the problem and now I am able to send the JSON data to the codebehind method using AJAX.

Migrating ASMX Service to WCF Service - AJAX Post

I have a asp.net asmx service and i would like to convert it to a wcf service.
I'm having problems calling the wcf service from jquery ajax POST request with parameters.
if i call the WCF service without parameters or pass the parameter in a json format it works OK.
When executing the below jquery post to the wcf service i get error 500.
Please note , i cannot change the way the jquery request is made.
Original ASMX Service:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void SendStatus(string param1, string param2)
{
..................
}
jQuery POST:
var d = { param1: 1, param2: 2 };
$.ajax({
type: "POST",
url: "/Service1.asmx/SendStatus",
data: d,
success: function () { }
});
NEW WCF Service:
[OperationContract]
[WebInvoke]
public void SendStatus(string param1, string param2)
{
}
jQuery POST:
var d = { param1: 1, param2: 2 };
$.ajax({
type: "POST",
url: "/Service2.svc/SendStatus",
data: d,
success: function () { }
});
-- EDIT --
I recall this issue drove me nuts once before, so I went back for another look. Sure enough ... Given the requirement that the Javscript remain as written, I maintain that this is literally impossible with the current release of WCF. Consider the following points:
1) You need to use webHttpBinding, because that's the only binding that supports REST style services (basicHttpBinding and WSHttpBinding both use SOAP wrappers). (ref. here: BasicHttpBinding vs WsHttpBinding vs WebHttpBinding)
2) The AJAX call as written in this question uses a content-type of "application/x-www-form-urlencoded" (you can confirm this using Fiddler).
3) You can also confirm that WCF throws an exception before the service method even gets invoked. The exception is as follows:
The body style 'Bare' is not supported by 'WebScriptEnablingBehavior'. Change the body style to be 'WrappedRequest'.
But "bare" body style is Microsoft-speak for a REST request using basic parameters (ie, not "wrapped" in JSON or XML). That is, there is no possible configuration that would allow WCF to handle this specific AJAX request. You can even implement your own WebContentTypeMapper, and it still won't work. This guy is on to them: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2473190-consider-making-the-system-servicemodel-channels-r
My conclusion is that (given you can't use MVC, which would make this a piece of cake), you need to somehow route this request to a basic .ASPX page, and use the trusty old Webforms methods (Page.IsPostBack, Request.Params["param1"], etc).
-- END EDIT --
Per the other thread above, looks like there are a few parameters you need to add/fix in your AJAX call:
...
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(d)
...
If you can't change the client-side code, you should not migrate these endpoints from ASMX to WCF. WCF uses a different, less-flexible serializer than ASMX and it's likely that you'll run into trouble that can only be resolved by changing how data is sent, received, and/or handled on the client-side.
If you're willing to deal with that turmoil anyway, a much better migration path would be waiting until ASP.NET Web API is shipped and moving to it. If you move to WCF now, you'll just be behind again later this year when Web API is released.
I think you have to pass string parameter values in double quotes (""). Like this:
var d = { param1: "1", param2: "2" };
$.ajax({
type: "POST",
url: "/Service2.svc/SendStatus",
data: d,
success: function () { }
});
Hope this will work.
500 error code means parameter values didn't match with required values.

Categories