HttpResponseMessage not showing JSON content from MVC relay to Web Api - json

I am using an MVC relay controller to call a Web Api controller to get around the PUT limitation in forms/browsers. The relay works fine. The problem is that the response when displayed just shows the response code and headers and not the JSON content that is also returned.
Here is the code that does the relay:
[HttpPost]
public async Task<HttpResponseMessage> UpdateTicket(int reference, TicketUpdateDTO ticket)
{
HttpClient client = new HttpClient();
var baseUri = string.Format("{0}://{1}{2}", Request.Url.Scheme,
Request.Url.Host, Request.Url.Port == 80 ? string.Empty : ":" + Request.Url.Port);
client.BaseAddress = new Uri(baseUri);
HttpResponseMessage responseMessage = await client.PutAsJsonAsync("api/Tickets/" + reference, ticket);
var content = await responseMessage.Content.ReadAsStringAsync();
return responseMessage;
}
And here is what is actually returned and displayed in a browser:
StatusCode: 201, ReasonPhrase: 'Created', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache X-SourceFiles: =?UTF-8?B?QzpcRGV2ZWxvcFxFeHRyZW1lSVRTXEV4dHJlbWVJVFNcYXBpXFRpY2tldHNcMTAwMDAwMg==?= Cache-Control: no-cache Date: Fri, 26 Feb 2016 16:32:57 GMT Location: http://localhost:59413/api/tickets/1000002 Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 419 Content-Type: application/json; charset=utf-8 Expires: -1 }
When I check the content, it is returning the object correctly in JSON format, but I am not sure why it isn't showing up in the browser with all the other parts of the HTTP response not shown.

Related

Save File And Json Data Via Angular and Spring boot

i have had this bug for a long peroid now, was trying to figure it out myself but am not getting it, it's an angular/spring boot app that am trying to upload different files and also save a json data at the same time, i have gone through previous questions concerning it but it hasn't worked for me, but when i tried saving the data via postman it works perfectly but not the same with angular, please i will appreciate the assistance...
this is my component.ts file containing the function
addBeat(artWork: File,untaggedmp3:File, taggedmp3:File){
const formData:FormData = new FormData();
if(artWork){
formData.append('artWork', artWork)
}
if(untaggedmp3){
formData.append('untaggedmp3', untaggedmp3)
}
if(taggedmp3){
formData.append('taggedmp3', taggedmp3)
}
this.beat.name = this.addBeatForm.get('name').value;
this.beat.price = this.addBeatForm.get('price').value;
this.beat.tempo = this.addBeatForm.get('tempo').value;
this.beat.description = this.addBeatForm.get('description').value;
this.beat.beatKey = this.addBeatForm.get('beatKey').value;
this.beat.mood = this.addBeatForm.get('mood').value;
this.beat.genre = this.addBeatForm.get('genre').value;
formData.append('beatDto', JSON.stringify(this.beat));
this.beatService.uploadBeat(formData)
.subscribe(
(data)=>{
console.log(data);
}
);
}
And my service.ts
public uploadBeat(formData: FormData): Observable<BeatDto>{
return this.httpClient.post<BeatDto>(`${this.apiServerUrl.admin}/api/beat/single/upload`, formData,
{headers: {
'Accept':'multipart/form-data',
'mimeType': 'multipart/form-data'}}
));
}
and my springboot rest controller is this
#RestController
#RequestMapping("/api/beat")
#AllArgsConstructor
#Slf4j
public class BeatController {
private final BeatService beatService;
private final FileStorageService fileStorageService;
#PostMapping(path = "/single/upload", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<BeatDto> uploadBeat(#RequestParam("beatDto") String beatDto,
#RequestParam("artWork") MultipartFile artWork,
#RequestParam("taggedmp3") MultipartFile taggedmp3,
#RequestParam("untaggedmp3") MultipartFile untaggedmp3){
BeatDto beatJson = beatService.getJson(beatDto,artWork,taggedmp3,untaggedmp3);
return ResponseEntity.status(HttpStatus.CREATED).body(beatService.uploadBeat(beatJson,artWork,taggedmp3,untaggedmp3));
}
}
so when i test in on the browser i get a error code 400 on the browser console...
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 400,
"statusText": "OK",
"url": "http://localhost:8081/api/beat/single/upload",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://localhost:8081/api/beat/single/upload: 400 OK",
"error": null
}
And also from my network tab
Request URL: http://localhost:8081/api/beat/single/upload
Request Method: POST
Status Code: 400
Remote Address: [::1]:8081
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Expose-Headers: Origin, Content-Type, Accept, Authorization
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: close
Content-Length: 0
Date: Thu, 06 Jan 2022 02:02:41 GMT
Expires: 0
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Accept: multipart/form-data
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 638
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryFUAjEynxdkQfpcfA
Host: localhost:8081
mimeType: multipart/form-data
Origin: http://localhost:4200
Referer: http://localhost:4200/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
main.app
#SpringBootApplication
#EnableAsync
#Import(SwaggerConfiguration.class)
public class BasicApplication {
public static void main(String[] args) {
SpringApplication.run(BasicApplication.class, args);
}
#Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Accept", "Authorization", "Origin, Accept", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
security config
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**", "/webjars/**", "/assests/**").permitAll()
.antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html")
.permitAll()
.antMatchers("/api/auth/**").permitAll()
.antMatchers(HttpMethod.GET,"/api/beat/**").permitAll()
.antMatchers(HttpMethod.POST,"/api/beat/**").permitAll()
.anyRequest()
.authenticated();
httpSecurity.addFilterBefore(jwtAuthFilter,
UsernamePasswordAuthenticationFilter.class);
}
Thanks In Advance

StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent,

{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Cache-Control: private
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Sat, 06 Jun 2020 02:26:17 GMT
Connection: close
Content-Type: text/html; charset=utf-8
Content-Length: 5059
}}
when calling a post method in api producing the response message without hitting the api,we are using stringcontent to pass input parameters as a serialized json which has 200k objects. our basic understanding is that its because content exceeds limited length. we are using .net core 3.1. how to increase the length of maximum allowed? we already tried placing [RequestSizeLimit(long.MaxValue)] on controller level. our web api call
[Route("~/api/Controller/somemethod")]
[HttpPost]
public string somemethod(List<DataMaster> Lists)
our api calling method
url = "https://localhost:44339/" + url;
HttpContent httpContent = new StringContent(inputParams, Encoding.UTF8, "application/json");
HttpRequestMessage request = new HttpRequestMessage
{
Method = new HttpMethod(method),
RequestUri = new Uri(url),
Content = httpContent
};
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
HttpClient client = new HttpClient(clientHandler);
return client.SendAsync(request).Result;
You can set the MaxRequestBodySize (docs):
Gets or sets the maximum allowed size of any request body in bytes. When set to null, the maximum request length will not be restricted in ASP.NET Core. However, the IIS maxAllowedContentLength will still restrict content length requests (30,000,000 by default). This limit has no effect on upgraded connections which are always unlimited. This can be overridden per-request via IHttpMaxRequestBodySizeFeature.
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = 2147483647;
});

windows phone 8.1 - api - sign up and login

I have got problem with using HttpClient in Windows Phone 8.1 application. I'm new in this WP 8.1 class.
I write this code:
var uri = new Uri("http://testapiurl.com");
var message = new
{
Name = "Test",
Surname = "Test",
Mail = "test#test.pl",
Password = "test1234"
};
var json_object = JsonConvert.SerializeObject(message);
HttpStringContent stringContent = new HttpStringContent(json_object.ToString(), UnicodeEncoding.Utf8, "application/json");
var httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(
uri,
stringContent);
Debug.WriteLine(response);
After compilation and running I got message
StatusCode: 200, ReasonPhrase: 'OK', Version: 2, Content: Windows.Web.Http.HttpStreamContent, Headers:
{
Connection: Keep-Alive
Server: Apache/2.4
Transfer-Encoding: chunked
Keep-Alive: timeout=10, max=100000
Date: Mon, 17 Aug 2015 04:59:02 GMT
X-Powered-By: PHP/5.4.39
}{
Content-Type: application/json; charset=UTF-8
}
In API help and examples I have information that in return it should be Status Code: 200 and name of created user. But I don't get it. Second thing is that when I push the second time the same code to create account I get back the same response. In help for API it should be error 409 conflict the same account already exist.
I don't know that this code is good, or am I missing big amount of code.
You need to use
var responseString = await response.Content.ReadAsStringAsync();
to get your response string. There will be everything from the actual response.
Your current code only writes the response headers and the content type.

Cannot get data with AngularJS + Azure WCF

I'm trying to get data from my website using AngularJS to my wcf in Azure but i'm getting error.
In my js:
$http({
url: dataService.serverPath + 'Services.svc/Login',
method: 'GET',
headers: { 'Accept': 'application/json, text/plain',
'Content-Transfer-Encoding': 'application/json;charset=utf-8',
'Accept-Charset': "charset=utf-8",
},
params: { key: key }
}).success(function (data, status, headers, config) {
//some code here
}
}).error(function (data, status, headers, config) {
$scope.hasError = true;
$scope.errorMsg = "The request failed: " + data;
});
fiddler response:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 11 Aug 2015 22:17:09 GMT
Transfer-Encoding: chunked
49
{"ID":0,"NomeUsuario":"Admin","IsAdmin":true,"Error":null}
0
Note, i'm getting HTTP 200 and i'm getting error.
The return data is 49 { Json } 0, what is it?
I tried to remove the Transfer-Encoding: chunked from my WCF but no success.
I spend this hole day trying getting data from Azure and i didnt. Running on my dev machine, it's fine and does not show Transfer-Encoding : Chuncked nor the 49 and 0 enclosure my JSON.
first thing that came to my mind was the MIME type as it needs to be changed by FTPing to your Website in Azure and updating the WebConfig file. But this usually returns 404 as in your case it returns 200, still no harm to check.
My other suggestion would be about the WebInvoke inside your WCF (if you are using it) following piece should set your WCF for Json usage.
[WebInvoke(UriTemplate = "Your template here",
Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebmessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
Hope this helps

Web api return null value

I have an Web Api controller for access data from server:
public class ServicesController : ApiController
{
[AcceptVerbs("POST")]
public IList<TreeMenuItem> LoadMetadata()
{
List<TreeMenuItem> itemsMenu = new List<TreeMenuItem>();
TreeMenuItem dataSource = new TreeMenuItem("1", "DataSources", null);
itemsMenu.Add(dataSource);
return itemsMenu;
}
}
which is call by an angularJS controler:
angular.module('App').
controller('TreeMenuController', ["$scope", "$http", treeMenuController]);
function treeMenuController($scope, $http) {
var baseUrl = "api/Services/LoadMetadata";
$http.post(baseUrl)
.then(function (result) {
$scope.roleList = result.data;
});
};
In browser network I have:
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate
Content-Length:2
Content-Type:application/json;charset=UTF-8
Request Payload
{}
Response Headers:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 4
in Response tab: [{}].
What is wrong?
I make it work:
The big help was the response message when I put in browser the address for accessing api services (api/Services/LoadMetadata):
The error answer was in an xml file where I found that was problem with serialization of the object TreeMenuItem. The advice was to decorate with DataContract the class and DataMember the class properties - like in WCF. After I did that (was need to add reference in project to System.Runtime.Serialization), everything was perfect.