I executed a WebService using Postman and it's executed correctly. And now i want to send a request to the WebService using Angular
Here is the Asp.net Web Service
This is the code for my WebService
public class Temperature : System.Web.Services.WebService
{
[WebMethod]
public double Farenheit(double celsius)
{
return (celsius * 9) / 5 + 32;
}
[WebMethod]
public double Celsius(double fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
}
And this is the screenshot on how i send a request using PostMan and it's working as expected
Screenshot for Calling the WebService using Postman
Here is the code for the Angular
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text/xml',
})
};
this.http.post('https://localhost:44389/Temperature.asmx/Celsius', '50', httpOptions)
.subscribe(res => {
console.log('Data: ' + res);
})
And this is the error I'm receiving
Error
"System.InvalidOperationException: Request format is invalid: text/xml.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
"
Message
Http failure response for https://localhost:44389/Temperature.asmx/Celsius: 500 OK
Name
"HttpErrorResponse"
Change your 'Content-Type': 'text/xml' to 'Content-Type': 'application/json'
try this :
import { HttpHeaders } from '#angular/common/http';
setHttpHeader() {
const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
let options = { headers: headers };
return options;
}
this.http.post('https://localhost:44389/Temperature.asmx/Celsius', '50', this.setHttpHeader())
.subscribe(res => {
console.log('Data: ' + res);
})
Related
I am trying to connect a WebAPI build using .Net core 5
Web API: method
// POST api/<BusController>
//[EnableCors("AllowAllHeaders")]
[HttpPost]
public JsonResult Post([FromBody]BusRequest busRequest)
{
var result = "Response Text";
return new JsonResult(result);
//return result;
}
Angular 13 Code
const busRequest = {
"StartDate" : "02/15/2022",
"EndDate": "02/17/2022",
"BusNo" :null
};
**Approach 1:**
const header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded;application/json; charset=utf-8');
header.set('Accept','application/json');
const options = {headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'}),
observe: 'response' as 'response',
responseType: 'json' as 'json',
body: busRequest};
this.http.request('post', 'http://localhost:55047/api/bus', options).subscribe();
**Approach 2:**
let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'});
this.http.post('http://localhost:55047/api/bus', JSON.stringify(Request), {headers: headers}).subscribe(data => {
console.log(data);
});
But nothing works.
Response is:
tatus: 415
title: "Unsupported Media Type"
traceId: "00-403257012c151a469a0e24b083d61d62-56ac63710daf8c45-00"
type: "https://tools.ietf.org/html/rfc7231#section-6.5.13"
Did anyone faced the similar problem?
I am setting up a new SignalR react app ("#aspnet/signalr") with Dot Net Core 2.0. I want to send custom headers to SignalR hub "negotiate" request (like request.headers["MyHeader"] = "Header").
I am able to connect to hub and get data back to react app. I have tried setting custom header by trying to overwrite httpClient in options passed to "withUrl".
With the code provided here I am getting error: "Error: Failed to complete negotiation with the server: Error: Unexpected status code returned from negotiate undefined"
It connects when httpClient is removed from options.
import { HubConnectionBuilder } from '#aspnet/signalr';
const options = {
accessTokenFactory: () => {
return "jwt token";
},
httpClient: {
post: (url, httpOptions) => {
httpOptions.headers = {
...httpOptions.headers,
MyHeader: "NewHeader"
};
httpOptions.method = "POST";
httpOptions.url = url;
return httpOptions;
}
}
};
const connection = new HubConnectionBuilder()
.withUrl("https://localhost:5001/chatHub", options)
.build();
connection.start().catch(function(err) {
console.log("Error on Start : ", err);
});
The way I see header as "Authorize": "jwt token", I expect to see another header in "https://localhost:5001/chatHub/negotiate" request as "MyHeader": "NewHeader"
Found answer to this.
httpClient.post overwrites the response of default SignalR httpClient.post.
Below update to httpClient worked.
httpClient: {
post: (url, httpOptions) => {
const headers = {
...httpOptions.headers,
MyHeader: "MyHeader"
};
return axios.post(url, {}, { headers }).then(response => {
return (newResponse = {
statusCode: response.status,
statusText: response.statusText,
content: JSON.stringify(response.data)
});
});
}
}
SignalR "negotiate" expects response in this form.
{
statusCode: 200,
statusText: "ok",
content: "<string response>"
}
I am trying to send JSON string from angular to asp.net server. I tried two things to get this data from client side.
1st : I have following code from both server and client side. I am sending a json string, and I expected to receive at backend for what I sent. However, I am just getting this server error before even getting the data.
POST "url" 404 (not found)
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:61476/api/testAPI/getData'.","MessageDetail":"No action was found on the controller 'getData' that matches the request."}
2nd : given that everything is same, i just added [FromBody] in my method like below. This doesn't return any server error and I am able to connect from my client side to server. However, I am getting my body message as null . I tried with Postman, but it seems that it works fine with Postman when I send same data.. I am aware that I can create some modelling in server code to match with my json string from client side, but I don't get why this doesn't work without modelling and also why connection fails without [FromBody].
All I need is to get JSON string from my client side. Can anyone please provide me advice on this?
public string getData([FromBody] string body)
angular
callServer(){
var json = {"name":"John Doe", "school": "A"};
let headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
this.appService.http.post('http://localhost:61476/api/testAPI/getData',
json,
{headers: headers})
.subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
})
}
server
namespace test.Controllers
{
public class testAPIController : ApiController
{
//
[HttpPost]
public string getData(string body)
{
try
{
Log.Info(string.Format("data {0}", body));
return "ok";
}
catch (Exception ex)
{
Log.Error(ex.Message);
return "error";
}
}
}}
Controller:
[HttpPost]
public string postData([FromBody]string body)
{
try
{
Log.Info(string.Format("data {0}", body));
return Json("ok");
}
catch (Exception ex)
{
Log.Error(ex.Message);
return "error";
}
}
Calling the server:
callServer() : Observable<string> {
var json = {"name":"John Doe", "school": "A"};
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let apiUrl = 'http://localhost:61476/api/testAPI/postData';
return this.appService.http.post(`${this.apiUrl}`, json, options)
.map((res: Response) => res.json())
.catch(this.handleErrorObservable);
}
private handleErrorObservable(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
Calling the service:
this._service.callServer()
.subscribe(
res => { console.log(res) },
err => { console.log(err) }
)
console.log(res/err) will be your response from the POST call. Sorry if misinterpreted your question but your question is a little hard to follow.
404 error is "not found". You must decorate your API Class
[Route("api/TestApi/[action]")]
public class testAPIController : ApiController
{
[HttpPost]
[HttpPost, ActionName("getData")]
public string getData([FromBody]string body)
{}
}
after merging angular app with asp.net MVC calling API from angular returns an empty JSON.
The angular and asp.net are in the same domain.
If I call the API With PostMan, I have a JSON with the result. but if I call it in the angular app my JSON result is empty.
Are there any tips for communicating angular app with asp.net MVC after merging and serving in the same domain?
Update 1:
The code that used to calling Webservice:
getSheets(): Observable<Sheet[]> {
return this.http.get(this.config.apiUrl + '/api/SheetsRelationAPI',
this.jwt())
.map(this.extractData)
.do(data => console.log('SheetsData:', data)) // debug
.catch(this.handleError);
}
/**
* Handle HTTP error
*/
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
// private helper methods
private jwt() {
// create authorization header with jwt token
const currentUser = JSON.parse(atob(this.cookie.getCookie('currentUser')));
if (currentUser && currentUser.access_token) {
const headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.access_token},
);
return new RequestOptions({ headers: headers });
}
}
private extractData(res: Response) {
const body = res.json();
return body || [];
}
Update 2:
I notice that my API if I called it from outside domain it respond 2 times:
inspecting network with google chrome inspect element:
the first response is "zone.js" initiator and the second response is an "other" initiator
If I call the API from inside of the Domain I just have a response from "zone.js" initiator and it returns an empty JSON.
Update 3
export class OtherComponent implements OnInit {
sheets: Sheet[] = [];
errorMessage: string;
constructor(private httpService: HttpService) {
// this.sheets = this.ichartHttp.getSheets();
// console.log(this.sheets);
}
getSheets() {
this.httpService.getSheets()
.subscribe(
sheets => this.sheets = sheets,
error => this.errorMessage = <any>error
);
}
ngOnInit() {
this.getSheets();
}
}
The Problem is with my Authentication methods,
I use two types of authentication, MVC and WebAPI they conflict if I send a request to API under the same Domain.
So my Answer is: Your Angular Code looks good, take a look at your middleware project
I'm trying to get basic authorization to work for a Get request, but I'm getting 2 exceptions:
OPTIONS http://localhost/drupal/user/1?_format=json
XMLHttpRequest cannot load http://localhost/drupal/user/1?_format=json. Response for preflight has invalid HTTP status code 405
I'm using angular2 with drupal 8 backend
here is my service
var _baseUrl = "http://localhost/drupal";
#Injectable()
export class DrupalService {
private actionUrl: string;
constructor(private _http: Http, private _apiUrl: DrupalApi) {
this.actionUrl = _baseUrl + _apiUrl;
}
authHeaders() {
let username = 'username';
let password = 'password';
let token = btoa(username + ':' + password);
var headers = new Headers();
headers.append('Authorization', 'Basic ' + token);
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return headers;
}
public GetSingle = (id: number): Observable<Response> => {
return this._http.get(this.actionUrl + id + '?_format=json'
, {headers: this.authHeaders()}).map(res => res.json());
}
}
but it works when I try the same request from postman app
how can I fix it?
In Postman, you are sending a header:
Authorization: Basic bXVyaGFmOmhleGFkZWNpbWFsMDU
But in angular you are passing:
headers.append('Authorization', 'Basic ' + btoa('bXVyaGFmOmhleGFkZWNpbWFsMDU'));
which will end up being:
Authorization: Basic YlhWeWFHRm1PbWhsZUdGa1pXTnBiV0ZzTURV
So, just don't convert the string to base64
headers.append('Authorization', 'Basic bXVyaGFmOmhleGFkZWNpbWFsMDU');
Update
Error code 405 means : Method Not Allowed, Which means, drupal does not allow OPTIONS requests. I've not worked with Drupal before. But, there should be a way to allow OPTIONS requests.