I am trying to call the following Web API method in Postman:
public HttpResponseMessage GetAllNotifications(HttpRequestMessage request, String Name)
{
HttpResponseMessage response = null;
try
{
List<ExpandoObject> res = _userProcess.GetAllNotifications(Name);
response = request.CreateResponse<List<ExpandoObject>>(HttpStatusCode.OK, res);
}
catch (Exception ex)
{
response = request.CreateResponse<string>(HttpStatusCode.BadRequest, "Unable to process your request Please contact administration");
throw new DataException(ex.Message.ToString());
}
return response;
}
Any advice appreciated.
Just run your Project in localhost and copy the Url from the Browser and add
your Api name , Example if the Project runs with an url like : https://localhost:3000/api/values
Just change the url with your api name in place of "values"
https://localhost:3000/api/GetAllNotifications and now paste this url in postman and set get method and click on send make sure your project is running in the same localhost port Number.
Related
When connecting via a non-secured protocol (http), my MVC 5 web application returns the error message properly. But the moment I connect via https, the error message is blank. Thought? NOTE: I try json return also. Thanks!
Browser debugger output
HTTP
HTTPS
MVC Controller:
string message = string.Join(" ", errors);
Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
return new HttpStatusCodeResult(Response.StatusCode, string.Join(" ", message));
Script:
function ajaxOnFailure(response, status, error) {
debugger;
if (response.status == 500) {
error = "An internal error has occurred. Please try again. If the problem persists, please contact IT."
}
toastr.error("", error);
}
I ended up using a workaround. Instead of return a fail response, I return OK response and determine the type of message via jquery. It would have been nice if a fail response return the message via https.
Scenario
I have an Angular 6 front end that communicates with a Spring Boot back end. The back end uses PostgreSQL as a database. The thing I want to do is to send a username to the data base and then return his email and print it on a page using Angular 6.
But, I am struggling with the Angular POST request where on subscribing to it I get a JSON parsing error in Chrome developer tools.
Code
Spring Boot
This works fine as I have tested it by printing the email returned from the database on the console.
#RequestMapping(value = "/reset", method = RequestMethod.POST)
public String resetMail(#RequestBody String username) {
try{
User user = userService.findByUsername(username);
//System.out.println(user.getEmail()); Testing purpose
return user.getEmail();
}catch(Exception e) {
//e.printStackTrace(); Prints out NullException StackTrace.
return "Not Present";
}
}
Angular 6
In the following code, I think the problem is in the subscription method as I am getting a JSON parsing error in Chrome developer tools.
httpOptions = { headers: new HttpHeaders({'Content-Type':'text/plain', 'Access-Control-Allow-Origin': '*'})};
reset(username:string) {
this.http.post('http://localhost:8090/reset', username, this.httpOptions).subscribe(data=> {
this.email = data as any;
});
}
console.log(this.email) // Prints undefined
Error
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8090/reset", ok: false, …}
>error: {error: SyntaxError: Unexpected token a in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "abcdefg#yahoo.com"}
>headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8090/reset"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8090/reset"
You want to serialize a string to JSON. If your controller would return an object the #RestController annotation would serialize it properly. In case you want to return just a string you have to return JSONObject.quote(user.getEmail()); You can get the JSONObject dependency from here http://mvnrepository.com/artifact/org.json/json
But I encourage you to always return objects as a response from your rest controllers.
Currently my client authenticates request only on case of 401 response:
this.client.authenticator(new okhttp3.Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credentials = authenticator.getCredentials();
if (credentials.equals(response.request().header("Authorization"))) {
throw new TraversonException(401, "Unauthorized", response.request().url().toString());
} else {
defaultHeader("Authorization", credentials);
Request.Builder newRequest = response.request().newBuilder()
.headers(Headers.of(defaultHeaders));
return newRequest.build();
}
});
But I'd like to change this behavior and be able to call it either manually or auto per first call? Is it possible somehow?
If the authentication is predictably required and not related to a proxy, then the solution is to implement an Interceptor instead of Authenticator.
OkHttpClient.Builder clientBuilder = ...;
clientBuilder.networkInterceptors().add(0, myInterceptor);
client = clientBuilder.build();
Example Interceptor https://github.com/yschimke/oksocial/blob/48e0ca53b85e608443eab614829cb0361c79aa47/src/main/java/com/baulsupp/oksocial/uber/UberAuthInterceptor.java
n.b. There is discussion around possible support for this usecase in https://github.com/square/okhttp/pull/2458. One issue with current Authenticator API is that it assumes a Response from the failed (401) request.
i have implemented GoogleAuthorizationCodeFlow scenario from google api client dotnet and tutorial to get token from what my client sent to server as a code. but when i call flow.ExchangeCodeForTokenAsync , I get the following error :
{"Error:\"invalid_grant\", Description:\"\", Uri:\"\""}
I read google authorization invalid_grant and gusclass oauth 2 using google dotnet api client libraries but they didn't help me and. I think it must be very simple but I don't know why it doesn't work.
For client side , I have used Satellizer and this is my server Codes:
public bool PostExchangeAccessToken(GoogleClientAccessCode code)
{
string[] SCOPES = { "email" };
IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets()
{
ClientSecret = "******",
ClientId = "********.apps.googleusercontent.com"
},
Scopes = SCOPES
});
try
{
TokenResponse token;
token = flow.ExchangeCodeForTokenAsync("*****#gmail.com", Newtonsoft.Json.JsonConvert.SerializeObject(code), "https://localhost:44301/",
CancellationToken.None).Result;
}
catch (Exception ex)
{
throw ex;
}
return true;
}
what is the problem?
On Github I found that I must use the Token from the client and use
GoogleAuthorizationCodeFlow.Initializer()
to create my UserCredential object.
You can check your google developer console settings.(Authorized redirect URIs)
Credentials => OAuth 2.0 client IDs => Your Application Settings => Authorized redirect URIs
You must add url. ("https://localhost:44301/")
My code :
flow.ExchangeCodeForTokenAsync("me", authCode, redirectUri, CancellationToken.None).Result;
Authorized redirect URIs
For use with requests from a web server. This is the path in your application that users are redirected to after they have authenticated with Google. The path will be appended with the authorization code for access. Must have a protocol. Cannot contain URL fragments or relative paths. Cannot be a public IP address.
My AJAX call is returning a 504 error when calling an ASP.NET Web API action.
More info:
Here's my API action:
public HttpResponseMessage Get(string fileName, int feedID)
{
try
{
// create file...
return new HttpResponseMessage { Content = new StringContent("Complete."), StatusCode = HttpStatusCode.OK };
}
catch (Exception ex)
{
Log.WriteError(ex);
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("An error has occurred.")
});
}
}
Here's my AJAX call:
$.ajax({
url: url,
type: 'GET',
success: function () {
$("#lblProgressDownload").hide();
window.open("Previews/" + fileName);
},
error: function (xhr, status, error) {
$("#lblProgressDownload").hide();
alert("Error downloading feed preview: " + error);
}
});
I get a 504 error (viewed in fiddler/ chrome console) when the file takes too long to create. The "error" parameter in the error callback doesn't return anything.
I only get the 504 error when it's hosted - on my dev it works fine.
How do I prevent this 504 error?
Note, I already tried changing the executionTimeout property in my web.config, as well as the ajax timeout. Neither worked.
HTTP error 504 is a gateway timeout:
The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI [...] in attempting to complete the request.
I suspect that means there is a proxy or gateway somewhere between you and the production server, but not your dev server, which is why it fails on the one but not the other.
Your choice is either to make your server code fast enough that it doesn't trigger the timeout, or get whoever is running the proxy server to relax their timeout restrictions (assuming it's something that you or your company controls).