Edited
I have a problem with communication between ASP.NET web service and react-native. I try to use ajax request after reading this: Simplest SOAP example and finally get error message.
Error code bellow:
"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0,
"_aborted": false, "_cachedResponse": undefined, "_hasError": true,
"_headers": {"content-type": "text/xml"},
"_incrementalEvents": false, "_lowerCaseResponseHeaders": {},
"_method": "POST", "_perfKey":
"network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx",
"_performanceLogger": {"_closed": false, "_extras": {},
"_pointExtras": {}, "_points": {"initializeCore_end": 11271328.84606,
"initializeCore_start": 11271264.66206}, "_timespans":
{"network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx":
[Object]}}, "_requestId": null, "_response": "Failed to connect to localhost/127.0.0.1:44358",
"_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false,
"_trackingName": "unknown", "_url": "http://localhost:44358/BikeWebService.asmx",
"readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, withCredentials": true
Ajax request in react native:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://localhost:44358/BikeWebService.asmx', true);
var sr ='<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">\
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/LogIn</Action>
</s:Header>
<s:Body>\
<LogIn xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">\
<password>a</password>\
<login>1</login>\
</LogIn>\
</s:Body>\
</s:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
}
console.log(xmlhttp);
}
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
In ASP.NET, I have a web method like this:
[WebMethod]
public ResponseModel<User> LogIn(string password, string login)
{
return new User();
}
I tried for this answer using axios, but still getting network error. Make request to SOAP endpoint using axios
I also try add cors to web.config as shown in this answer: How to allow CORS for ASP.NET WebForms endpoint?
But it's still not working...
SSL is disabled in ASP.NET service. I try to disabled firewall and tls in windows but this is not a problem
I'm running on ASP.NET 4.8
Does anybody have any idea? Is XMl okey? I have it from WCF test client.
Starting web service on IIS and add address to hosts on windos fix this connection error.
SOAP request:
let body = '<?xml version="1.0" encoding="utf-8"?>\
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">\
<soap12:Body>\
<LogIn xmlns="http://tempuri.org/">\
<password>string</password>\
<login>string</login>\
</LogIn>\
</soap12:Body>\
</soap12:Envelope>';
let SOAPAction = 'http://tempuri.org/LogIn';
requestOptions = {
method: 'POST',
body: body,
headers: {
Accept: '*/*',
'SOAPAction': SOAPAction,
'Content-Type': 'text/xml; charset=utf-8'
},
};
await fetch('http://ip:port/BikeWebService.asmx', requestOptions)
.then((response) => console.log(response))
.catch((error) => {
console.log('er' + error)
});
Related
i acan use ajax and api action in one project and send data and update data correctly.
but when i want to send data from ajax in my project to api action in my another project,the api action dont work!
$.ajax({
type: "post",
url: urll,
error: function() {
alert("errore")
},
data: {
id: 4
},
success: function(dataa) {
alert("ok");
var x = JSON.stringify(dataa, null, '\t');
var dataaa = $.parseJSON(x);
alert(dataaa.price);
dataa.price -= 1.02;
var url2 = 'https://localhost:44337/api/apiialbums/PutAlbum';
//var url2 = 'http://localhost:51111/api/AlbumsApi/PutAlbum';
$.ajax({
type: "PUt",
//async: false,
url: url2,
//data: JSON.stringify(dataa, null, '\t'),
data: {
album: dataa
},
//contentType: "application/json; charset=utf-8", ///////
//dataType:"json",
success: function(dataaz) {
alert("updated");
alert(dataaz.price);
var x2 = JSON.stringify(dataaz, null, '\t');
alert(x2);
},
error: function() {
alert("error in update..");
}
})
}
});
and my api [httpput]action:
[HttpPut]
public async Task<ActionResult<Album>> PutAlbum([FromBody]Album album)
{
_context.Entry(album).State = EntityState.Modified;
await _context.SaveChangesAsync(); return album;
}
when i breakpoint in api action,
I understand that the program does not refer to the action
I searched the internet a lot but I could not find the reason, please help me to solve this problem as soon as possible
It's quite probable that you haven't enabled cross-origin requests. As it is stated here:
Browser security prevents a web page from making AJAX requests to another domain. This
restriction is called the same-origin policy, and prevents a malicious
site from reading sensitive data from another site. However, sometimes
you might want to let other sites call your web API.
So you have to enable first Cors. For that reason, you should go in the WebConfig class of the WebAPI that you want to be called and put the following line anywhere inside the Register method:
config.EnableCors();
Then you should go the controller, in which the PutAlbum is defined and decorate with the following attribute
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "PUT")]
You should replace "http://mywebclient.azurewebsites.net" with the URI of your Web Application, that you want to call your Web API.
UPDATE
The above apply for ASP.NET projects. For ASP.NET Core please have a look at here.
in my asp.net core project, i use following code in ConfigureServices in startup:
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("*")/*.AllowAnyOrigin()*/.AllowAnyHeader().AllowAnyMethod();
});
});
in we can use the client url instead of * :
.WithOrigins("http://localhost:51111")
and in startup in Configure use :
<pre> app.UseCors();</pre>
I am working with TWILIO and Sharepoint 2016 to send text messages. I have created a Studio Dashboard to send the text messages and a Twilio function to send a response back to a Sharepoint list. My website is external facing with FBA accounts
All of this works if I paste the FEDAUTH code in my function. My question is how do I get the FEDAUTH code ? The pasted FEDAUTH seems to expire after awhile.
exports.handler = function(context, event, callback) {
var options = {
"method": "GET",
"hostname": "www.mysite.org",
"port": null,
"path": "/_layouts/15/Login.aspx",
"headers": {
"authorization": xxxx,
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
sendAPI();// passed FEDAUTH to /_api/contextinfo/
});
});
req.end();
};
At times I have an endpoint on my web api:
[HttpPost]
public async Task Foo([FromForm] int[] a, [FromForm] int b, ...) {
await Task.Delay(1000);
}
When calling this from the client side using axios:
var formData = new FormData();
formData.append('a', this.selected.map(n => n.id));
formData.append('b', this.id);
await this.axios.post('/api/v1/foo', formData);
I get a 400 error. Which states in no way of which field caused the issue. Is there a way of finding out other than trial and error?
POST https://localhost:5001/api/v1/foo 400 (Bad Request)
For Asp.Net Core Api, if you check the web browser network tab, you will see below which already return the expected error response.
{
"errors": {
"a": [
"The value '1,2,3' is not valid."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "8000001e-0004-fe00-b63f-84710c7967bb"
}
If you want to capture the errors by axios, you could try
var formData = new FormData();
formData.append('a', "1,2,3");
formData.append('b', "1");
axios.post('/api/values/Foo', formData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(JSON.stringify(error.response.data.errors));
});
I have the following code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static MyResponse myMethod(ParameterClass parameters)
{
MyResponse resp = new MyResponse();
resp.errors.Add("Some error message");
HttpContext.Current.Response.StatusCode = 400;
return resp;
}
running this with jQuery.ajax using url MyPage.aspx/myMethod this call does not return my payload from MyResponse object. Once i switch the statuscode to 200 the return works using the success callback in ajax, but i want to return custom error messages with 4xx and 5xx status codes, how to make it work.
It looks like IIS is the problem, but what do i have to do to still allow returning my class objects on error?
Update 1: i also watched network tab in chrome, IIS is not returning the payload at all, so jQuery cannot be the problem.
Update 2: my jquery ajax call
$.ajax({
url: 'MyPage.aspx/myMethod',
data: JSON.stringify({ parameters: request }),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
...
},
error: function (data) {
// data.responseJSON is undefined and data.responseText contains only HTTP status code text, like "Bad Request" when code was 400.
}
});
Ok found it in another stackoverflow post.
The solution was to add the following to web.config:
<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
<clear/>
</httpErrors>
By default IIS is replacing the response on error, here the attribute "existingResponse=PassThrough" is the key. Now responseJSON and responseText is filled with my custom content returned by the webmethod.
Found in HttpResponseMessage content lost when HTTP Status is Bad Request
When I send this token to Controller in WebApi I get information 401 (Unauthorized) Why? I take this token form login and it`s correct.
$scope.expiresCookie = $cookies.get('expires');
$scope.issuedCookie = $cookies.get('issued');
$scope.access_tokenCookie = $cookies.get('access_token');
$scope.expires_inCookie = $cookies.get('expires_in');
$scope.token_typeCookie = $cookies.get('token_type');
$scope.user_nameCookie = $cookies.get('user_name');
$scope.addLink = "http://localhost:56305/api/ProductInsuranceCar";
$http({
method: "GET",
url: $scope.addLink,
headers: { 'Authorization': '' + $scope.token_typeCookie + ' ' + $scope.access_tokenCookie + '' },
headers: { 'Content-Type': 'application/json; charset=utf-8' }
}).then(function mySucces(response) {
$scope.test = response;
}, function myError(response) {
});
Picture 1
Picture 2
Example correct request
When I use Advanced Rest Client I get information but in my method :/ not working...
Correct answer. Position of header is important :/
headers: { 'Content-Type': 'application/json; charset=utf-8' },
headers: { 'Authorization': $scope.Authorization2 }
The problem could be when calling web api from a different UI domain.
Cookies are not sent if domains are different. So, If you call from localhost:64757 to localhost:56305 cookies are not sent, that's why you are receiving Unathorized 401 error.