POST 500 Internal Server Error - asp.net

I'm going mad with this error.
POST
http://localhost:56105/Home/getContactbyId?ConId=%225%22 500 (Internal Server Error)
Hope you'll be able to help me. I need to get Contact data based on ContactId. Following is the relevant code (apologies if I missed something, I'll add if needed):
contactController.js
ContactsApp.controller("contactController", function ($scope, $rootScope, $routeParams, $location, myService) {
function getContactById(id) {
var getting = myService.get_Contact_By_Id(id);
getting.then(function successCallback(response) {
$rootScope.Name = response.data.Name;
}, function errorCallback(response) {
    return "Error";
       });
   }
 function init() {
var contactId = $location.path().split("/")[2];
    console.log(contactId); //this loggs the correct Id
getContactById(contactId);
}
init();
}
myService.js
ContactsApp.service("myService", function ($http) {
this.get_Contact_By_Id = function (ConId) {
console.log(ConId); //this logs the correct id
return $http({
method: 'post',
url: '/Home/getContactById',
params: {
ConId: JSON.stringify(ConId)
}
});
}
}
HomeController.cs
public class HomeController : Controller
{
public string getContactById(int ConId)
{
int id_int = Convert.ToInt32(ConId);
using (ContactsDBEntities contactsData = new ContactsDBEntities())
{
var theOne = contactsData.Contacts.Where(x => x.Id == id_int).FirstOrDefault();
return theOne.Name;
}
}
}

Using JSON.stringify(ConId) returns a quoted string with the ConId number. params expects a simple object with name : value pairs. Simply use
params: {
ConId: ConId
}
When the ConId is sent using stringify(), the Convert.ToInt32(ConId) call will throw an Exception for conversion (expected NUMBER, not 'NUMBER'). You should put some validation after using that conversion, or a try - catch block.
Also it could be a problem with returning FirstOrDefault() if no result is found. You should check also the theOne variable before using it.
You should check the server application log (Application Event Viewer) to see the exception causing the HTTP Error 500.

Related

Meteor publication send custom sanitized error to client in publication

I am not sure if I am just doing something wrong or if this is actually not working. I want to display the original publication error on the client, in case I catched one:
Meteor.publish('somePub', function (args) {
const self = this
try {
// ... publication logic
catch (pubErr) {
self.error(pubErr)
}
})
On the client I am "catching" this error via the onStop callback:
Meteor.subscribe('somePub', args, {
onStop: function (e) {
// display e to user
}
})
However, while on the server the pubErr is a Meteor.Error and according to the documentation it should be sent to the client, the client just receives a generic sanitized error message:
on the server
{
stack: "useful stack of actual method calls",
error: "somePub.failed",
reason: "somePub.invalidArguments",
details: { arg: undefined }
}
on the client
{
stack: "long list of ddp-message calls",
isClientSafe: true,
error: 500,
reason: "Internal server error",
details: undefined,
message: "Internal server error [500]",
errorType: "Meteor.Error"
}
Note: I also tried to add the error to itself as sanitizedError field, as in the documentation mentioned, but no success either.
Am I missing something here?
Actually I found the answer to the issue after being pointed into the right direction.
The example code works fine on a new project, so I checked why not in my project and I found, that I did not surround the arguments validation using SimpleSchema by the try/catch (unfortunately my question was poorly designed as it missed this important fact, mainly because I abstracted away the schema validation from the publication creation):
Meteor.publish('somePub', function (args) {
pubSchema.validate(args) // throws on fail
const self = this
try {
// ... publication logic
catch (pubErr) {
self.error(pubErr)
}
})
So I thought this could not be the issue's source but here is the thing: Simple Schema is not a pure Meteor package but a NPM package and won't throw a Meteor.Error but a custom instance of Error, that actually has the same attributes (error, errorType, details) like a Meteor.Error, see this part of the source code of a validation context.
So in order to pass the correct information of a SimpleSchema validation error to the client you should
wrap it in a try/catch
add the isClientSafe flag to it
alternatively convert it to a Meteor.Error
Attach a custom Meteor.Error as sanitizedError property to it

Angular 2 http service. Get detailed error information

Executing Angular2 http call to the offline server doesn't provide much info in it's "error response" object I'm getting in the Observable's .catch(error) operator or subscription error delegate (they are both share the same info actually). But as you can see on the screen shot of the console there's actual error was displayed by zone.js somehow.
So, how can I get this specific error info (net::ERR_CONNECTION_REFUSED)?
Thanks.
Whenever server do not respond, response.status will be always equal to 0 (zero)
{
type: 3, //ResponseType.Error
status: 0, // problem connecting endpoint
}
Also note, when you are performing CORS request, but origin (url in browser) is not authorized (not in allowed list of host names configured in remote endpoint) the response would be similar to above, with exception to type attribute which will be equal to 4 = ResponseType.Opaque...
This means, connection was made, but for instance, OPTIONS request returned with headers which do not contain origin or HTTPS request was performed from HTTP origin.
You can handle the error messages so they are easier to read. This can definitely be expanded on too:
public Get() {
return this.http.get(this.URL).map(this.extractData)
.catch(this.handleError);
}
public extractData(res: Response) {
let body = res.json();
return body || {};
}
public handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
Check out this part of the docs on error handling.
Without digging in the code, my expectation is that if the server is unreachable, then no response can be returned from the server. Therefore the Response object remains its initialized state.

HTTP.call throws errors instead of returning response

I am working with the Facebook graph API and have run into trouble regarding handling failed requests.
I use this code to create a new post
SocialFacebook.createPosting = function(data) {
var options = {
params: {
access_token : data.tokens.accessToken,
message : data.text
}
};
var url = 'https://graph.facebook.com/' + data.graphId + '/feed';
var response = HTTP.call('POST', url, options).data;
return response;
}
But instead of returning a JS object with error information in the response, it throws an error on failed requests
Exception while invoking method 'createPosting' Error: failed [500] {"error":{"message":"Duplicate status message","type":"FacebookApiException","code":506,"error_subcode":1455006,"is_transient":false,"error_user_title":"Duplicate Status Update","error_user_msg":"This status update is identical to the last one you posted. Try posting something different, or delete your previous update."}}
Because it's wrapped in an Error, the otherwise JSON object is now a string with some other stuff appended to it, which makes it difficult to parse and extract the attributes
Any idea as to why it throws an error, instead of returning a JS object with error details like usually?
Much appreciated
According to the docs, about HTTP.call():
On the server, this function can be run either synchronously or asynchronously. If the callback is omitted, it runs synchronously and the results are returned once the request completes successfully. If the request was not successful, an error is thrown.
So there you have it: since you called HTTP.call() synchronously (without providing a callback), if it responds with an error (in your case, Code 500) the error is thrown and not included in the data.

Breeze query error, even though results returned

Breeze is calling the "fail()" function, even though the data seems to be returned from the odata service (as well as being in the error object). There are 5 "transactions" returned from the ODATA service (as seen in Chrome developer tools) as well as in the "data" property of the error object being passed to the fail function.
Calling code looks like this:
function getTransactions() {
var query = breeze.EntityQuery.from("Transactions")
.take(5);
return entityManager.executeQuery(query,
function(data) {
log("transaction Query success!");
var transactions = data.results;
},
function(err) {
log("Query failed:" + err.message);
});
}
I am at a loss as to what is wrong that is causing the "fail()."
There IS a Transaction constructor defined, code below:
function registerTransactions(metadataStore) {
metadataStore.registerEntityTypeCtor('Transaction', Transaction);
// constructor -- empty
function Transaction() { };
Object.defineProperty(Transaction.prototype, 'itemCount', {
get: function () {
return 0;
}
});
}
Note the url for the odata resource is "Transactions" but the entity is Transaction. What are the reasons why the "Fail() function would be called?
Error.message = "; " which isn't helping much.
I believe I am on the latest Breeze 1.4.11 and datajs 1.1.2
After much research, I found the problem was another funcky CORS setting on the service side. I was able to figure it out by going directly to dataJS against the same service, and getting a more informative error message.
What you MUST do on the service side is something like this:
var cors = new EnableCorsAttribute("*", "*", "*", "DataServiceVersion, MaxDataServiceVersion");
The last parameter has to with the service sending the OData version in the header and thereby allowing the client to determine if it can handle the specified version of OData.
If anyone knows more details about this, feel free to comment.

Authentication and Custom Error pages

I have a site that is using Azure ACS for authentication, backed by ADFS. When things are going well and people do things they are supposed to its great but that doesn't happen always so we have been implementing custom error pages.
The problem is, it doesn't seem to catch authentication errors, such as
ID3206: A SignInResponse message may only redirect within the current web application
Key not valid for use in specified state.
These errors still produce the ugly yellow error screen no matter what I say in my web.config. They are clearly ASP.NET errors and not IIS errors, so my question is how and where can I put custom error pages to display such errors in a 'pretty' way, as setting a page in web.config isn't working?
EDIT: To be clear, we have ACS set up to use an error page, have customErrors on with a different error page, neither or being used.
You have to have an action on a controller in your web app that accepts a POST from ACS and takes a parameter of type string. You must also configure your relying party application in ACS to point to that action for errors. Then in the action code you can do something like this:
namespace ASPNETSimpleMVC.Controllers
{
public class ErrorController : Controller
{
// Errors can be mapped to custom strings here.
static Dictionary<string, string> ErrorCodeMapping = new Dictionary<string, string>();
static ErrorController()
{
ErrorCodeMapping["ACS50019"] = "You chose to cancel log-in to the identity provider.";
ErrorCodeMapping["ACS60001"] = "No output claims were generated. You may be unauthorized to visit this site.";
}
//
// POST: /Error/
//
// If an error occurs during sign-in, ACS will post JSON-encoded errors to this endpoint.
// This function displays the error details, mapping specific error codes to custom strings.
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Index( string ErrorDetails )
{
// The error details contain an array of errors with unique error codes to indicate what went wrong.
// Additionally, the error details contain a suggested HTTP return code, trace ID, and timestamp, which may be useful for logging purposes.
ErrorDetails parsedErrorDetails = new JavaScriptSerializer().Deserialize<ErrorDetails>( ErrorDetails );
ViewData["ErrorMessage"] = String.Format( "An error occurred during sign-in to {0}. ", parsedErrorDetails.identityProvider );
// Loop through all ACS errors, looking for ones that are mapped to custom strings.
// When a mapped error is found, stop looking and append the custom string to the error message.
foreach ( ErrorDetails.Error error in parsedErrorDetails.errors )
{
if ( ErrorCodeMapping.ContainsKey( error.errorCode ) )
{
ViewData["ErrorMessage"] += ErrorCodeMapping[error.errorCode];
break;
}
}
return View( "Error" );
}
}
}
You may also find this article helpful.

Resources