How to know client URL name? - c#

I have created web-api to provide service like pin-code, Bank IFSC Code and so on, from my website named as http://www.ajaxserver.com
My all api is hosted on my site and my all client access using my site.
web api code is
[Route("api/GetURLName/")]
[HttpGet]
public string GetURLName(HttpRequestMessage request)
{
return HttpContext.Current.Request.Url.AbsoluteUri ;
}
One of my client website name is http://www.clientwebsite.online
client is used jquery to retrieve info like below code.
$('#btnTestCore').click(function () {
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName/',
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
Output comes:
"http://ajaxserver.com/api/GetURLName/".
Need Output:
"http://clientwebsite.online/api/GetURLName/"

You could append the output to your AJAX request:
$('#btnTestCore').click(function () {
var urlname = encodeURI("http://clientwebsite.online/api/GetURLName/")
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName?urlname=' + urlname,
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
You will then, of course, have to read that querystring in your webAPI code

As far as the server of the ajax request knows; the "site" is itself, so http://www.ajaxserver.com. You could try to look at the referrer, but... that isn't reliable across all browsers and protocols.
So you have two choices:
have the client API tell you the calling site - note that it could trivially be spoofed by the client
do some non-trivial proxy (etc) configuration such that the ajax server's site responds on the client domain
Note that http://clientwebsite.online/api/GetURLName/ was not the actual URL and is not going to come from anywhere by itself.

Related

Posting Multipart and string content web API using Ajax in Asp.net

I have multipart content web API. which is working fine.and tested in postman.
Now i am trying to consume that web api in my asp.net web application using ajax post method. I referred some coding in google and applied. but it shows error finally. i don't know what's the misake i am doing. I am using .Net Framework 4.5. My coding and postman execution of my api as Below .
var data = new FormData();
jQuery.each(jQuery('#fileupload')[0].files, function (i, file) {
data.append('file', file);
});
data.append('siteCode', 'HQ');
data.append('phoneNumber', '95878784XXX');
data.append('customerCode', 'C001');
data.append('notificationFlag', '1');
$.ajax({
type: 'POST',
url: SequoiaUri + "api/profilePicture",
contentType: "application/json; charset=utf-8",
data: data,
dataType: "json",
Cache: false,
processData: false,
success: function (data) {
alert("Picture Uploaded Successfully!");
}
Can anyone help me what's the error in my ajax post method...
try this:
$.ajax({
url: SequoiaUri + "/api/profilePicture",
data: data,
type: 'POST',
//enctype: 'multipart/form-data', // try if still is not working
contentType: false,
processData: false,
success: function (data) {
alert("Picture Uploaded Successfully!");
},
.....

ASP.NET + jQuery AJAX - getting 500 server error

I want to call an ASP.NET function from jQuery by AJAX with response.
I have file Controll.aspx where is included javascript code. Next I have /Services/ControllService.asmx, where is the function, which I want call from js.
js code:
$(document).ready(function () {
$('#btn_start').on('click', function () {
$.ajax({
type: "POST",
url: "Services/ControllService.asmx/Start",
data: {},
dataType: "json",
async: true,
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (err) {
alert("Error:" + err.toString());
}
});
});
});
But I still getting the error 500.
POST http://localhost:56000/Services/ControllService.asmx/Start 500 (Internal Server Error)
k.cors.a.crossDomain.send
n.extend.ajax
Do you have any hints, what do I need to set e.g. in Web.config?
Many thanks.
SOLVED:
1 - I have defined Start function in ControllService.asmx.cs as static.
2 - I have badly configured data. It has to be named by the same way e.g. "sth".
In javascript it should be:
...
url: "Services/ControllService.asmx/Start",
data: JSON.stringify({ sth: "hahaha" }),
dataType: "json",
...
and in ControllService.asmx.cs -> method Start
public string Start(string sth){}
Many, many thanks for your hints.

Calling REST Api with JSONP & JQuery

I have created REST API in MVC4, it is working fine when I compose request from fiddler. But in my application, I need to call through jsonp because it would cross domain request. But when I'm calling this service it gives me error as shown below:
Jquery JsonP Call ..
$.ajax({
type: "POST" ,
url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf&callback=?",
data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
cache: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (callback)
callback(response.d);
},
error: function (response) {
if (callback)
error(response.d);
},
});
Error:
Right now you are not doing JSONP. It's still POST request. To make it JSONP you need simply to add dataType: "jsonp" to you $.ajax() call. You can also remove some other redundancy parameters like content-type and 'callback' param (but that's optional). So, your code should looke like:
$.ajax({
url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf",
data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
datatype: "jsonp",
cache: false,
success: function (response) { /* ... */ },
error: function (response) { /* ... */ },
});
Be also ready, that your request will be transformed to a GET one and will look like
/GetDomainAvailability?apikey=key&callback=jquery123&SubDomain=sss&ParentDomain=ppp&ResellerId=123&_=4398572349857
So, prepare your server-side code for that.

In Visual Studio C#, is there a way to apply Web Config Transforms to Javascript files?

In Visual Studio, I have some Javascript code on a site I'm developing. While I'm debugging I'm using the $ajax call to "localhost". When deployed, it will need to be the actual server:
$('#textInput_UserName').focusout(function () {
var _username = $('#textInput_UserName').val();
$.ajax({
url: 'http://localhost:8809/Account/UserNameExists/',
data: { username: _username },
dataType: 'html',
});
When I publish, I need to transform that localhost to the actual domain:
$('#textInput_UserName').focusout(function () {
var _username = $('#textInput_UserName').val();
$.ajax({
url: 'http://www.mydomain.com/Account/UserNameExists/',
data: { username: _username },
dataType: 'html',
});
Is there an easy/automatic way to do this, similar to the way Web Config transforms work?
Many thanks!
You don't, you just omit the host, the browser will fill this in for you, like this:
$('#textInput_UserName').focusout(function () {
var _username = $('#textInput_UserName').val();
$.ajax({
url: '/Account/UserNameExists/',
data: { username: _username },
dataType: 'html',
});
If you're actually talking about x-domain requests, which I doubt you are, then just set a global js site variable.
I recommend you to use this:
url: '<%= ResolveClientUrl("~/Account/UserNameExists/")',
If you do it this way you'll avoid problems if you:
install the app in a virtual directory instead of the domain root
move your page to a different directory level in your app
use your service from a master page or user control, which can be instantiated in different pages, an thus directory levels
You can also expose a public property in your page/user control/master page, and use it from code in the same way, i.e:
code in the page/uc/master: public string ServiceUrl { get { return ResolveClientUrl("~/Account/UserNameExists/");}
code in .aspx: url: '<%= ServiceUrl',
Are you making a call to a web service or what is the destination of this url?
When I am working with ajax calls in my web applications I usually set up the methods inside of a web service and call them like this:
$.ajax({
type: "POST",
url: "../Services/BookingService.asmx/GetVerifiedReservations",
data: paramsJson,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
invalidDays = $.parseJSON(response.d);
},
error: function (xhr, textStatus, thrownError) {
alert(textStatus);
alert(thrownError);
}
});
As you can see the path is relative to the rest of the files in your domain.

How do I return the current domain of my project in javascript and ASP.NET?

I have some javascript that requires a specific URL to call an ASP.NET web service.
When I run the application locally, the url is something like: http://localhost:123456/ProjectName/Default.aspx
But when I upload the application, the domain will change to:
http://myDomain.com/Default.aspx
What's the best way to capture the current URL path and pass it in as a variable to my javascript? Here is my javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#autoComplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:123456/ProjectName/Default.asmx/SkillsList", //CHANGE THE URL!!
//url: "http://myDomain.com/Default.asmx", //The other URL...
data: "{'like':'" + request.term + "'}",
datatype: "json",
async: true,
success: function(data) {
response(data.d);
},
error: function(result) {
alert("error");
}
});
},
minLength: 2
});
});
</script>
I'm using ASP.NET if that helps at all.
Thanks!
post to relative path
url: "/ProjectName/Default.asmx/SkillsList"
Looks like you're writing out to the aspx page. Given that, you should be able to just have ASP.Net tell you via something like
url: "<%= Request.ApplicationPath%>/Default.asmx/SkillsList"

Categories