Adding custom header to generated WebService helper - c#

Is the a way to add or customize the headers when using the generated javascript that is created from .asmx files?
For example I have a webservice like:
SomeService.asmx
[WebService(Namespace = "https://www.somedomain.com/api/someapi", Description = "api", Name = "someapi")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
[HttpPost]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<SomeModel> GetData(string SomeArgument)
{
string customHeaderValue = HttpContext.Current.Request.Headers.Get("SomeCustomHeader");
// Do things
}
}
Now using jQuery I can specify the custom header like:
jQuery.ajax({
type: 'POST',
url: '/Path/ToFile/Webservice.asmx/GetData',
data: "data",
success: OnSuccessFunc,
error: OnFailureFunc,
headers: {
'SomeCustomHeader': "SomeCustomHeaderValue" <---
}
});
But I know that the asmx files can generate some helper functions javascript that will handle everything for me. For example if I add
<script type="text/javascript" src="/Path/ToFile/Webservice.asmx/js"></script>
then on the page i can simply write
<script type="text/javascript">
Webservice.GetData("data", OnSuccessFunc, OnFailureFunc)
</script>
But how would I include the custom header data using the generated javascript version?

You can try to setup a header to every request using beforeSend hook with $.ajaxSetup()
Take a look at this URL.
https://www.edureka.co/community/82342/how-to-add-custom-http-header-to-ajax-request-with-javascript

Related

Is It possible to use web method in C# class?

I'm using web method in C# class file(i.e not a partial class of any web form) and I have html file. I just want to call web method from html file using JQuery AJAX GET and POST methods. Is it possible to do this? Is this have any sense? or i must want use asp web form?
To answer your question it's important that you first understand the prurpose of having a web service.Web services allow us to expose any piece of software over the internet and allow clients to consume it.
In .NET ASMX web services we expose software to the outside world by decorating methods with the [WebMethod] attribute.But even if we apply the [WebMethod] attribute our method will not be available over the internet unless it's inisde a:
.asmx web service file
.aspx web page
Hopefully now you understand why you can't simply define a [WebMethod] inside a standard C# class.Below is a simple example of calling an ASMX web service from a plain html page:
MyService.asmx:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string GreetUser(string name)
{
return String.Format("Hello {0}",name);
}
}
Index.html:
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCallService").click(function () {
$.ajax({
type: "POST",
url: "MyService.asmx/GreetUser",
contentType: "application/json;charset=utf-8",
data: '{name:"' + $("#txtName").val() + '"}',
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" value="Call Service" id="btnCallService" />
</body>
</html>
Yes you can. Your html file can include a tag with functions that make ajax calls.
Here is a simple example from W3School's site:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
You see that the button has an 'onClick' event, which calls the loadDoc function.
And this is the function:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Here is the link to the tutorial's page:
http://www.w3schools.com/ajax/
Your Ajax Call on HTML will look very similar to this
var options = {
type: "POST",
url: '<%=ResolveUrl("~/FileLocationWhereWebMethodIsDefined") %>',
data: "{'Add Parameters if your web method needs it'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
//jQuery(".overlay").show();
//jQuery(".progress").show();
},
success: function (msg) {
},
error: function (jqXHR, textStatus, errorThrown) {
// jQuery(".overlay").hide();
// jQuery(".progress").hide();
throw Error; // "error";
}
};
jQuery.ajax(options);

ASP .NET MVC3 ajax call same function from various pages

How can I call the same action using ajax from different pages?
type: 'POST',
url: 'Notification/GetRecentNotifications/'
I'm currently using the code above to call my action. It works for my application's home page, but when I change to other page, this doesn't work. Can anybody give me a solution? Thanks before.
Heres what I usually do to point to which controller & action to call within an ajax jquery call...
$.ajax({
type: "POST",
url: '#(Url.Action("Action", "Controller"))',
success: function (data) {
}
});
Use Url.Action() to build links
Put the code in a ajax.js file in your scripts directory then reference it in the pages where you need to use the methods in that file. Then, put any server side logic for your ajax calls in an AjaxController For example:
ajax.js
function foo() {
var model = { };
$.ajax({
url: '#Url.Action("Foo", "Ajax")',
type: "POST",
data: JSON.stringify(model),
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
}
AjaxController.cs
public class AjaxController : Controller
{
[HttpPost]
public JsonResult Foo(FooModel model)
{
string message = _ajaxService.Foo(model);
return Json(message);
}
}
In the example above _ajaxService is a service layer object that contains the logic to handle your ajax requests. Below is how to use the function in your view:
SomeView.cshtml
<script type="text/javascript" language="javascript" src="#Url.Content("~/Content/Scripts/ajax.js")"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#button').click(foo);
});
</script>
If there is additional logic to pass data to the ajax method that is reused, you should probably put it in a partial view and reference that from every view that needs it.

posting string data back via webservice using ajax and jquery

all,
I'm trying to pass html data up to a webservice that exists in .NET/c#. I'm using JQUERY but continue to get an error of "failed posted data". Is my syntax wrong in either my ajax script or in my code behind? Thanks for any help.
$(function () {
$("[id$=rdbSaveAjax]").click(function () {
var markedUPHTML = $("[id$=wrapper]").html();
var postData = "{'HTMLData' : '" + markedUPHTML + "'}";
$.ajax({
type: "POST",
url: "Role.asmx/test",
data: JSON.stringify({html: postData}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(JSON.stringify(postData));
}
});
});
});
webservice code behind:
/// <summary>
/// Summary description for Role
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Role : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string test(string html)
{
string strHTMLData = html;
return html;
}
}
var postData = "{'HTMLData' : '" + markedUPHTML + "'}";
This will not build a proper string if markedUPHTML has single or double quote in it. Use JavaScript escape method before concatenating. Try this
var postData = "{'HTMLData' : '" + escape(markedUPHTML) + "'}";
And then while passing the data you dont have to strigify it because its already a string. Just try this
data: { html: postData }
Try public static string on the server side, instead of public string
all,
I ended up finding the issue by using firebug. Everytime I tried posting back to connect to the test method in my Role.asmx file, I would get a 500 error. My solution is a Cassini project so I could not do much with configuring my local IIS site to change permissions.
Instead, I created a method in my code behind and placed [WebMethod] right above the method name. In my code behind I did not setup any declarations that you would typically see after adding a webservice file to your solution.
[WebMethod]
public static bool test(string strHTMLMarkup)
{
....code
}
I hope this helps anyone other there.
Thanks.

Reading XML data from ASMX webservice for Jquery autocomplete

Me and ASMX web services do not get on. We argue. She brings up arguments we had in the past. It's a pain. Our relationship is on the rocks!
I have an ASMX web service, which I haven't serialised with the Newtonsoft library (as explained why here: http://encosia.com/2011/04/13/asp-net-web-services-mistake-manual-json-serialization/). It looks like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
var dict = AtomicCore.CityObject.GetCitiesInCountryWithStateAutocomplete(isoalpha2, prefixText);
string[] cities = dict.Values.ToArray();
return cities;
}
Simple enough right? It return this when searching for new:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<string>New Orleans, Louisiana</string>
<string>New York, New York</string>
</ArrayOfString>
I was expecting JSON, but after a bit of reading, it seems I shouldn't try and serialise the output - it should just happen right? Anyway, so I have the following JQuery on the frontend:
$('#<%=txtCity.ClientID%>').autocomplete('<%=ResolveUrl("~/AtomicService/Assets.asmx/GetCitiesWithState")%>', {
dataType: 'json',
httpMethod: 'POST',
contentType: 'application/json; charset=utf-8',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.d.length; i++) {
rows[i] = { data: data.d[i], value: data.d[i].Value, result: data.d[i].Value };
}
return rows;
},
formatItem: function (row, i, n) {
return row.Value;
},
extraParams: {
minChars: 2,
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
maxRows: 20,
prefixText: function () {
return $('#<%=txtCity.ClientID%>').val()
}
},
max: 20
}).result(function (event, data, formatted) {
if (data) {
alert(data['Key']);
}
});
I can see the calls using Chrome:
And yet stuff all happens! There is no Jquery errors, no fireworks, no anything. She is ignoring me.
At first I was blaming the webservice, but I think this may have more to do with how I'm parsing and formatting the data in jquery.
So, my question is, what am I doing wrong and how can I make the autocomplete work correctly?
Help appreciated :)
EDIT: It may not be helpful, but this is what I see in Fiddler:
The jQuery UI autocomplete does not anymore use the formatItem method. That and many other such methods were present in autocomplete's earlier version that was a plugin here
I have rewritten your code using the jQuery UI's autocomplete and it works for me with the below htm and asmx files.
Refer to the demos on the jQueryUI autocomplete for more methods you could use.
I have used the json2.min.js from www.json.org
Also I have added the [System.Web.Script.Services.ScriptService] attribute to the Service1 class so that it could directly be invoked from jQuery as a json web service.
These articles helped me:
ASMX and JSON – Common mistakes and misconceptions
Using jQuery to Consume ASP.NET JSON Web Services
3 mistakes to avoid when using jQuery with ASP.NET AJAX
The htm file
<!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>jQuery to ASMX</title>
<link rel="Stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/cupertino/jquery-ui.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://localhost/Scripts/json2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#txtInput").autocomplete({
source:function (request, response) {
var paramters = {
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
prefixText: request.term
};
$.ajax({
url: 'Service1.asmx/GetCitiesWithState',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramters),
success: function(data) {
response($.each(data.d, function(index, value) {
return {
label: value,
value: index
}
}));
}
});
},
minLength:2,
delay:500
});
});
</script>
<p>
Hello, World!</p>
<label for="txtInput">
Enter the string here:</label><input type="text" id="txtInput"/>
</body>
</html>
The asmx file
using System.Web.Script.Services;
using System.Web.Services;
namespace jQueryAutoCompleteBackEnd
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service1 : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
return new string[] { "New Orleans, Lousiana", "New York, New York" };
}
}
}
The reason that the asmx webmethod is returning XML rather than JSON is because the HTTP method is GET rather than POST.
In order for the autocomplete plugin to use POST you'll have to implement the source parameter using a callback function, see here

ASMX webservice not returning JSON, can only POST using application/x-www-form-urlencoded contentType

I can call my webservice using jQuery IF the contentType = "application/x-www-form-urlencoded; charset=utf-8"
This will, however, return the xml: <string>[myjson]</string>
If I try to POST to the service using "application/json; charset=utf-8" I receive a 500 error with an empty StackTrace and ExceptionType. My webservice function is never hit so I'm not quite sure how to debug this situation.
My methods and classes are decorated with the appropriate attributes and are set to use JSON as their response type (as do my wsdl and disco files). I have the Ajax extensions installed and the required entries in web.config.
This is on a SharePoint farm, but I'm not sure that makes too much of a difference. I deployed the web.config changes on all WFE's as well as installed the ajax extensions. Again the service works, it just will not accept anything but the default content type.
Not sure what I'm missing here, fellas...
my ajax call:
$.ajax({
type: "POST",
url: "/_vti_bin/calendar.asmx/Test",
dataType: "json",
data: "{}",
contentType: "application/json; charset=UTF-8",
success: function(msg){
alert(msg);
},
error: function(xhr, msg){ alert(msg + '\n' + xhr.responseText); }
});
My webservice class:
[WebService(Namespace = "http://namespace")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]
public class CalendarService : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Test()
{
return "Hello World";
}
}
I have this working in 2.0 using web services, but I have put in place protection from the .d (see dataFilter below). I also am returning an array of objects. NOTE: the class for the object is static, or it would not work correctly for me at least.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ModifierCodesService.asmx/GetModifierList",
success: function(msg)
{
LoadModifiers(msg);
},
failure: function(msg)
{
$("#Result").text("Modifiers did not load");
}
});
Here is a snippett of my web service:
...
[WebService(Namespace = "http://mynamespace.com/ModifierCodesService/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class ModifierCodesService : System.Web.Services.WebService
{
/// <summary>
/// Get a list of Modifiers
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true)]
public Modifier[] GetModifierList()
{
return GetModifiers();
}
/// <summary>
/// Modifiers list from database
/// </summary>
/// <returns></returns>
private Modifier[] GetModifiers()
{
List<Modifier> modifier = new List<Modifier>();
ModifierCollection matchingModifiers = ModifierList.GetModifierList();
foreach (Modifier ModifierRow in matchingModifiers)
{
modifier.Add(new Modifier(ModifierRow.ModifierCode, ModifierRow.Description));
}
return modifier.ToArray();
}
}
...
the object code:
public static class ModifierList
{
/// <summary>
/// Returns the Modifier Collection.
/// </summary>
/// <param name="prefix"></param>
/// <returns></returns>
public static ModifierCollection GetModifierList()
{
I have been fighting with this today with an iPhone app talking to a .Net Web Service.
I found that if I changed my Content Type to application/jsonrequest it went through without a problem and I was able to process the data in my web server.
Just for grins I added the line mentioned above to my web.config, but it did not make application/json work.
not sure if it could be this simple but I am using jQuery to call back JSON from my web methods.
the main difference I see is the attribute of the class
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://MyNameSpace")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Web : System.Web.Services.WebService{
[WebMethod]
public string TestMethod(){
return "Testing";
}
}
I have to assume you are using the 3.5 framework because that is the only way to expose JSON web methods.
My calls form jQuery look virtually identical, so no issue there.
If you're testing this in IE, try removing the charset declaration from your contentType attribute (i.e. it should look like this:
contentType: "application/json",
I have yet to discover why, but IE seems to get its knickers in a twist when making JSON calls with the "charset=UTF-8" part.
I think you're looking for the WebInvoke or WebGet Attribute, it lets you specify Uri Template, body style, request and responseformats, for example:
[WebGet(ResponseFormat= WebMessageFormat.Json)]
This Link may help. There's a similar article for WebInvoke (used mostly for post).
I use JQuery AJAX JSON calls to ASMX webservice quite a bit. It works perfectly in all browsers. I'm using .NET 2.0 with the ASP.NET AJAX Extensions installed (bundled in 3.5).
My class has the same decorators as your. My methods only have the [WebMethod(EnableSession = true)] decorator. My web.config however has the following entry in its httpHandlers section:
<add verb="*" path="*jsonservice.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
My jquery call looks as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "path/to/service/jsonservice.asmx/MethodName",
data: JSON.stringify(DTO),
dataType: "json",
success: function(rtrn) { alert("good"); },
error: function(req, msg, err) { alert("bad"); }
});
This article is the root of my knowledge.
Looks like you have to specify json as the response format in the scriptMethod tag. This is from vb.net, but I'm sure you get the idea:
ResponseFormat:=ResponseFormat.Json

Categories