I have 2 Web API controllers:
1. Runtime1Controller
2. Runtime2Controller
In Runtime2Controller:
public HttpResponseMessage PostCreateRequest(KeyRequest keyRequest)
{
try
{
Runtime1Controller runtime1Controller = new Runtime1Controller();
HttpResponseMessage response = runtime1Controller.PostCreateRequest(keyRequest);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
catch(Exception ex)
{
throw;
}
}
In Runtime1Controller, I return HttpResponse message:
public HttpResponseMessage PostCreateRequest(KeyRequest keyRequest)
{
// Process Data .....
Request.CreateResponse(HttpStatusCode.Created, keyRequest);
}
Then, why All the time Request is NULL. If I directly call Runtime1Controller PostCreateRequest, it is not NULL. Why SO???
in Runtime1Controller, use return when you create the response (or maybe you dont put this part):
public HttpResponseMessage PostCreateRequest(KeyRequest keyRequest)
{
// Process Data .....
return Request.CreateResponse(HttpStatusCode.Created, keyRequest);
}
Related
I am calling an url using ajax - but when it is called I am getting response HTTP/1.1 403
below is my calling code
function callApi() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "http://103.240.91.110/GENCLASS/checkApi.do?
$95599&99&3456790&09012020152103*", true);
xmlhttp.send();
}
Below is the server side method who is sending the response
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward(); // return value
ApiForm apiForm = (ApiForm)form;
try {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
// send back response
System.out.println("true");
}catch(Exception e){
errors.add(ActionErrors.GLOBAL_ERROR, new org.apache.struts.action.ActionError("load.error.unknown"));
//log.error("Critical Error " + e);
}
if (!errors.isEmpty()) {
saveErrors(request, errors);
forward = mapping.findForward("failure");
} else {
forward = mapping.findForward("success");
}
return (forward);
}
Whenever I am calling the URL I am getting response HTTP/1.1 403
Note that It is working perfectly when I am requesting through browser
I am using tomcat 8.5 on windows on server (called resource)
Any assistance will be appreciated
The following method is intended to accept an Http method and url, execute the method against the url, and return the resulting response to the caller. It returns ActionResult because there are error conditions that need to be handled.
At present, the method only tells the caller whether the call succeeded or not, it doesn't return details about the response from the downstream server. I would like the caller to receive the entire response (including status code, response body, etc) from the call.
How can I convert the HttpResponseMessage to something appropriate to return via ActionResult?
[HttpGet(#"{method}")]
public async Task<IActionResult> RelayRequest(string method, [FromQuery] string url)
{
var httpMethod = new HttpMethod(method);
Uri uri;
try
{
uri = new Uri(url);
}
catch (Exception e)
{
return BadRequest("Bad URL supplied: " + e.Message);
}
var request = new HttpRequestMessage(httpMethod, uri);
try
{
var response = await _httpClient.SendAsync(request);
// WANT TO RETURN (ActionResult)response HERE! <<<<<<<<<<
if (response.IsSuccessStatusCode)
{
return Ok();
}
return BadRequest(response);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
It's going to depend a little bit on the response you're receiving from your await _httpClient.SendAsync(request) but you could deserialize the response Content from the request and return that from your controller.
For example, if the request used JSON, you could do the following:
if (response.IsSuccessStatusCode)
{
// Assuming the use of Newtonsoft.Json
var responseBody = JsonConvert.DeserializeObject<RequestResponse>(await response.Content.ReadyAsStringAsync());
return Ok(responseBody);
}
I have an APIController Method as below. Basically I need to validate an API response. So it's an API call within an API call.
public class DCController : ApiController
{
[HttpPost]
public HttpResponseMessage SampleMethod(string url)
{
var uri = new Uri(url);
var baseAddress = uri.GetLeftPart(System.UriPartial.Authority);
var apiAddress = url.Replace(baseAddress + "/", "");
var responseString = string.Empty;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(apiAddress).Result;
if (response.IsSuccessStatusCode)
{
responseString = response.Content.ReadAsStringAsync().Result;
}
}
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().Validate())
{
return Request.CreateResponse(HttpStatusCode.OK, "Validated");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid");
}
}
Issue:
1. Request object is null in the return lines.
2. If i try creating a request object -
var request = new HttpRequestMessage();
It throws below error:
An exception of type 'System.InvalidOperationException' occurred in
System.Web.Http.dll but was not handled in user code
Additional information: The request does not have an associated
configuration object or the provided configuration was null.
Not sure what settings I need to add. I am relatively new to working with APIs. Any help is appreciated.
I could get it working by below code -
[HttpPost]
public HttpResponseMessage Get(string url)
{
string responseString = GetWebApiData(url); //Extracted the method
HttpResponseMessage response = new HttpResponseMessage();
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().Validate())
{
response.ReasonPhrase = "Valid";
response.StatusCode = HttpStatusCode.OK;
}
else
{
response.ReasonPhrase = "Invalid";
response.StatusCode = HttpStatusCode.BadRequest;
}
return response;
}
I'm making an ASP.NET MVC call to a method via AJAX and the error throws an exception. I'd like the message of the exception to be passed back to the client, and I'd prefer not to have to catch the exception. Something like this:
[HttpPost]
public ActionResult AddUser(User user) {
if (UserIsValid(user)) {
return Json(new { resultText = "Success!" });
}
throw new Exception("The user was invalid. Please fill out the entire form.");
}
I'm seeing in my firebug response an HTML page
<!DOCTYPE html>
<html>
<head>
<title>"The user was invalid. Please fill out the entire form."</title>
.....
I'd like to not be forced to use a try catch block to do this. Is there a way to automatically get the jQuery $(document).ajaxError(function () {} to read in this exception message? Is this bad practice? Can I override the controller OnException? Or do I have to try/catch and return JSON?
Something like this would be nice:
$(document).ajaxError(function (data) {
alert(data.title);
});
You can do this with a custom filter:
$(document).ajaxError(function(event, jqxhr) {
console.log(jqxhr.responseText);
});
-
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
if (isTrue)
{
return Json(new { Foo = "Bar" });
}
throw new HttpException(404, "Oh noes...");
}
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
var statusCode = new HttpException(null, exception).GetHttpCode();
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
Data = new
{
error = true,
message = filterContext.Exception.Message
}
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = statusCode;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
Somewhat inspired by this blogpost: http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc
Rather than handle an exception that was raised by the server, why not have a flag in the JSON response?
[HttpPost]
public ActionResult AddUser(User user) {
if (UserIsValid(user)) {
return Json(new { success = true, resultText = "Success!" });
}
return Json(new { success = false, resultText = "The user was invalid. Please fill out the entire form." });
}
I've an Ajax code, through which i want to send securely a private access_token to a url via http POST, how to achieve this using below given code??
function getstatus(url, placeid, access_token)
{
if(window.XMLHttpRequest)
{
xmlRequest = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
try
{
xmlRequest = new ActiveXObject("Msxm12.xMLHTTP");
}
catch(e)
{
try
{
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlRequest = false;
}
}
}
xmlRequest.open("GET",url,true);
xmlRequest.onreadystatechange = function()
{
if(xmlRequest.readyState==4)
{
if(placeid == "adminstatus")
adminstatus.innerHTML=xmlRequest.responseText;
if(placeid == "dbview")
{
dbview.innerHTML=xmlRequest.responseText;
}
}
}
xmlRequest.send();
}
Consider the parameter "access_token" in the function getstatus is to be http POST-ed!
Take a look at XMLHttpRequest, assuming you are attempting to send the data as key/value pairs,
xmlRequest.open("POST",url,true);//use the post method
xmlRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");//set the content type
...
xmlRequest.send("access_token="+encodeURIComponent(access_token));//send the token