Read Content-Disposition: form-data; name="json" using .net core + AWS - amazon-elastic-beanstalk

I have integrated my .net-core MVC application with a third-party system for a callback hit.
When i host the above application in Azure my API works as expected but when I host it AWS elastic beanstalk it does not work.
In Azure input for API comes as an object but in AWS it case as below
Below is the request I am receiving from third-party to my call back API.
------------------------------e2bdba1d3cf0
Content-Disposition: form-data; name="json"
{"Transaction":{"Guid":"[Fax GUID]","To":"14154847140","From":"14154847140","IsInbound":false,"IsDraft":false,"TypeCode":"F","StatusCode":"S","ErrorCode":null,"CreatedAt":"1505933982","UpdatedAt":"1505934022","Uri":"\/v1\/Accounts\/[Your Account GUID]\/Transmissions\/[Fax GUID]","NumPagesBilled":1}}
------------------------------e2bdba1d3cf0--
My API Code
[HttpPost]
[Route("CallBack")]
public string CallBack()
{
try
{
eSignService eSignService = new eSignService();
dynamic json = new StreamReader(HttpContext.Request.Body).ReadToEndAsync().GetAwaiter().GetResult();
if (json != null)
{
//logic to save the file
}
else
{
_logger.LogInformation("No Data Found");
}
}
catch (Exception ex)
{
_logger.LogInformation("Error : " + ex);
}
string result = "Hello API Event Received";
return result;
}

Related

Angular 2+ - Handle JAVA Rest 401 response

Angular service.ts:
getExcel() {
let link: string = (this.url);
return link;
}
component.ts:
public getExcel() {
//checks if string is empty, undefined or not null
if (this.langCode) {
return window.open(this.avrs.getExcel());
}
}
Java rest.java
#GET
#Path("/excel")
#Produces("application/vnd.ms-excel")
public Response getTransportCostsExcel(
#Context HttpServletRequest request,
) {
byte[] excelInBytes = excelGen.getExcel();
if(excelInBytes == null){
return Response.status(Response.Status.NOT_FOUND).entity("No data").build();
}
//Header details
String contentType = "application/vnd.ms-excel";
Response.ResponseBuilder responseBuilder = javax.ws.rs.core.Response.ok((Object) excelInBytes);
responseBuilder.type(contentType);
responseBuilder.header("Content-Disposition", "attachment; filename=" + fileName);
//Returns Excel
return responseBuilder.build();
}
When I try calling my api from postman i get "No data" and status is 401 not found. So the rest method works fine.
I get my excel file if data is found. But I can't seem to handle the 401 response. Angular opens a new window and says
site not avaliable: ERR_INVALID_RESPONSE
As you can see im not using http.get cause I want the user to start downloading the excel if the file is found.

convert json web Api response to soap response

I have an exist web API project, I have requirement to wrap the web api services in soap services.
I create web service project. I called there to the web api, and got the response as json.
now' my question is, how to convert the json response to wsdl/soap response
code:
[WebMethod]
public string Test2(GetMessagesRequest product)
{
return CreateProductAsync(product);
//return "";
}
static string CreateProductAsync(GetMessagesRequest product)
{
System.Net.ServicePointManager.Expect100Continue = false;
var client = new HttpClient();
var res = client.PostAsJsonAsync(#"http://localhost:99/api/messaging/post/", product).Result;
object data = res.Content.ReadAsAsync<object>().Result;
return new JavaScriptSerializer().Serialize(data);
//HttpResponseMessage response =
// response.EnsureSuccessStatusCode();
// return URI of the created resource.
// return response.Headers.Location;
}
Thanks

Configuration IIS 7 for JSON

i have this code for receiving data from server:
try
{
var data = _model.GetAll().ToList();
if (data.Count > 100)
return SendMessage($"Too much results", HttpStatusCode.Forbidden);
var result = JsonConvert.SerializeObject(data,
new JsonSerializerSettings { Converters = new JsonConverter[] { new StringEnumConverter() } });
return SendMessage(new{ results = result });
}catch (Exception ex)
{
return SendMessage("Server error.", HttpStatusCode.InternalServerError);
}
SendMessage method:
protected JsonResult SendMessage(string message, object data, HttpStatusCode code = HttpStatusCode.OK)
{
Response.StatusCode = (int)code;
return Json(new { message, data }, JsonRequestBehavior.AllowGet);
}
When method return 403 http code, i localhost is everything ok. Method send data in content-type application/json. But when I deploy my code to web server (IIS 7) method send content-type text/html and data is empty.
Where is problem? How i must configure IIS server?
Thanks for advices
Here is solution for my problem: https://forums.iis.net/t/1213176.aspx.
Open your IIS > click web site > Error Pages > here under "Alerts" section click on "Edit Features Settings..." it will show following three option :
1] Custom error pages
2] Detail errors
3] Detailed errors for local requests and custom error pages for remote requestes.
select 2nd option Detail errors click Ok.

android volley does not receive php json object

I'm using android volley for send request to server side, in the other hand on server side I use php.
Here is my android code to receive response from server(does not matter what params is, because I do not need params on server side yet!):
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("ATA d Response", response.toString());
VolleyLog.v("ATA Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ATA Response", " RESPONSE ERROR");
VolleyLog.e("Error: ", error.getMessage());
}
});
req.setShouldCache(false);
queue.getCache().clear();
queue.add(req);
Now, when in server side i return as response something like this:
if( isset($_POST)) {
echo json_encode(array("x"=>"y", "m"=>"n"));
exit();
}
every this is ok, and response is what server sends!
But! when in server side I return as response something like this:
if( isset($_POST)) {
echo json_encode(array(array("0"=>"1"),array("2"=>"3"),array("4"=>"5")));
exit();
}
Response is not ok and get this error:
06-17 02:28:53.456 D/Volley: [1296] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] MY_URL 0xa64d9c1b NORMAL 1> [lifetime=3645], [size=60], [rc=200], [retryCount=0]
06-17 02:28:53.466 D/ATA Response: RESPONSE ERROR
06-17 02:28:53.466 E/Volley: [1] 2.onErrorResponse: Error:
What's wrong with my code?
Try sending a content type header. application/json should do the job.
header("Content-type:application/json");
send header before producing any outputs (i.e before echo statement).

Spring MVC either sending JSON or Redirecting to another page

Hello I have been using Spring 3 for my project, I have been stuck in on point.
if(ajax){
User user = userTemplate.getUser(form.getCreator_id());
int isPremium = user.getPremium();
if ( isPremium == 1 ){
Map<String,String> resultMap = new HashMap<String,String>();
response.setHeader("Access-Control-Allow-Headers", "*");
response.addHeader("Access-Control-Allow-Origin", "*");
resultMap.put("result", "success");
return new Gson().toJson(resultMap);
}else{
return "redirect:/f/redirectedUrl?url="+form.getWeb_page();
}
}
redirectedUrl controller is just for redirecting, but if the request is ajax request then i want to response the request as json.
How can I achieve this, thanks.
Edit : I can understand if request is ajax or not. My problem is if it is ajax i want to response json, if it is not then i want to redirect.
Use this code in your controller to identify if request is ajax or not and based on that you can add your logic.
boolean ajax = "XMLHttpRequest".equals(
getRequest().getHeader("X-Requested-With"));
You can decide it from header("X-Requested-With") of your httpRequest object.
public ModelAndView getDetails(HttpServletRequest request, HttpServletRespone response) {
if(ajax) {
try {
new MappingJacksonHttpMessageConverter().write(object, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
} catch(Exception e) {
logger.error("Error when converting to json");
}
return null;
} else {
return new ModelAndView("viewName");
}
}