I built a website using ASP.NET MVC and Knockoutjs. This is hosted on IIS on Windows Sever 2012. There is another web application where I use ajax to POST and that application does not give any errors. The Submit button on the website is binded using the click bind to this function. This works when I run it in Debug mode on the localhost.
self.SubmitEvaluation = function () {
reqUrl = "/Home/SubmitEvaluation";
$.ajax({
type: "POST",
url: reqUrl,
data: JSON.stringify({ evaluation: ko.toJSON(self) }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response == 1) {
self.EvalComplete(true);
} else {
self.EvalComplete(false);
alert("Submission Failed. Please resubmit!!!")
}
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].'+exception.toString());
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
In the home controller I have these two web methods.
[HttpGet]
public string Test()
{
Logger.Logger.WriteLog("Test", "Inside Test");
TestModel product = new TestModel();
product.Name = "Apple";
product.Price = "3.99M";
return JsonConvert.SerializeObject(product);
}
[HttpPost]
public int SubmitEvaluation(string evaluation)
{
Logger.Logger.WriteLog("Submitevaluation", "Inside SubmitEvaluation");
int result = -1;
try
{
EvaluationModel eval = JsonConvert.DeserializeObject<EvaluationModel>(evaluation);
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string sql = "INSERT INTO xyz table blah blah blah";
MySqlCommand cmd = new MySqlCommand(sql, conn);
result = cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Logger.WriteLog("Submitevaluation", ex.ToString());
}
return result;
}
I receive Internal Sever Error 500 from the Ajax request when I click on the Submit button.
But if I do this http://xxx.xxx.xxx.xxx/Home/Test I get the json result back {"Name":"Apple","Price":"3.99M"}.
Response header from Fiddler
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Jan 2014 16:22:16 GMT
Content-Length: 276
After turning on customer errors and detailed error message I am receiving this message.
Could not load file or assembly 'MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The system cannot find the file specified
I downloaded the Mysql connector from http://dev.mysql.com/downloads/connector/net/ and I added the assembly by right clicking on References > Extensions and selecting the 4.0 version. I also tried the 4.5.
Uninstalled 6.8 and downloaded 6.7. Works now.
Related
My API has a method of type Patch that I need to call from the client. This method is:
[HttpPatch("{id}")]
public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument<Reservation> patch)
{
Reservation res = Get(id);
if (res != null)
{
patch.ApplyTo(res);
return Ok();
}
return NotFound();
}
I am trying to call it from my client whose code is:
[HttpPost]
public async Task<IActionResult> UpdateReservationPatch(int id, Reservation reservation)
{
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:8888/api/Reservation/" + id),
Method = new HttpMethod("Patch"),
Content = new StringContent("[{ \"op\":\"replace\", \"path\":\"Name\", \"value\":\"" + reservation.Name + "\"},{ \"op\":\"replace\", \"path\":\"StartLocation\", \"value\":\"" + reservation.StartLocation + "\"}]", Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(request);
}
return RedirectToAction("Index");
}
I am failing to do so and getting error.
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Tue, 28 Jul 2020 12:25:24 GMT
Content-Type: application/problem+json; charset=utf-8
Content-Length: 370
}}
What can be the problem?
I am calling web method using ajax call.Here is the example call.
[WebMethod(true)]
public static string Save(string customParams)
{
throw new ApplicationException("Example Exception");
}
$.ajax({
url: url,
type: "POST",
data: data,
contentType:"application/json; charset=utf-8",
dataType: props.dataType ? props.dataType : "text",
error: function (xhr, errorType, ex) {
debugger;
err(ex);
}
})
If that method throws an exception I only get 500 internal server error.Stacktrace is empty and I can't get the inner exception message.I decorated webmethod with try catch blocks and return HttpException and set text of it but it didn't work.
try
{
throw new ApplicationException("Example Exception");
}
catch (Exception e)
{
throw new HttpException(500,e.Message,e);
}
I also tried this solution again with no luck.
catch (Exception e)
{
HttpContext.Current.Response.Write(e.Message.ToJsonString());
HttpContext.Current.Response.StatusCode=500;
}
By the way I also experimented that uncaught exception when request is ajax request can't be caught by Global.asax's Application_Error.Here is the issue.
I switched custom error off.Now it's displaying error but still not a intented solution.
Any solution ? Thanks in advance.
I found some way of achieving this.As you may notice I am changing 500 error responseText with the actual exception's message and stacktrace.
First Clear Response and Header.Then set TrySkipIisCustomErrors = true in order to not let asp.net to return 500 error page.After that write actual error message to the response,flush it and end processing page.I really don't know this is ideal way of doing but so far I only got this solution.
Here is the code.
public static string ProcessAjaxException(Exception ex)
{
if (!HttpContext.Current.Request.IsAjaxRequest())
{
return null;
}
var page = (Page)HttpContext.Current.CurrentHandler;
string url = page.AppRelativeVirtualPath;
Framework.Core.Logging.LoggerFactory.Error(url, ex);
var jsonExceptionDetails = new { ex.Message, ex.StackTrace, statusText = "500" };
var serializedExcpDetails = JsonConvert.SerializeObject(jsonExceptionDetails);
//Erases any buffered HTML output.
HttpContext.Current.Response.Clear();
//Erases header
HttpContext.Current.Response.ClearHeaders();
/*If the IHttpResponse::SetStatus method was called by using the fTrySkipCustomErrors flag,
* the existing response is passed through,
* and no detailed or custom error is shown.*/
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.StatusCode = 500;
//Send all buffered output to client
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Write(serializedExcpDetails);
//Stop processing the page
HttpContext.Current.Response.End();
return null;
}
While accessing web Api in xamarin.forms i am getting this error below which is i am unable to Solve
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET Date: Fri, 09 Feb 2018 12:50:00 GMT
Content-Type: text/html Content-Length: 1245 }}
This is my web Api Code.
public IList<TCourse> GetData()
{
try
{
using (var context = new HCMSEntities())
{
var cli = (from b in context.tblTrainingCourses
orderby b.CourseID
select new TCourse { CourseID = b.CourseID, Course = b.Course }
).ToList();
return cli;
}
}
catch (Exception ex)
{
return null;
}
}
And here is the code which is consuming the api and i am getting above error.
public async Task Index()
{
List<TCourse> EmpInfo = new List<TCourse>();
try
{
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri("http://10.20.2.62/");
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("api/Course");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
EmpInfo = JsonConvert.DeserializeObject<List<TCourse>>(EmpResponse);
}
}
}
catch (Exception e)
{
}
}
The web Api is not deployed.I tried http://localhost/ in base address than i switched to Ip.
no idea whats wrong and where.
kindly Guide.
I have created the simple login page in xamarin.forms,i have API for those logins,while running at postman iam getting the output,but while logging from the simulator iam getting the following error.
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: private
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=639506ba4afdd530b4429c0d57e89977accb4b666a1e17dbe3fcc5c1fce369d5;Path=/;HttpOnly;Domain=snovahub.azurewebsites.net
Date: Wed, 13 Sep 2017 13:23:00 GMT
Content-Length: 3485
Content-Type: text/html; charset=utf-8
}}
My Api method is as follows:
#region Get results from api
public static async Task<T> GetResultFromApi<T>(string serviceUrl,bool isTrue=true)
{
try
{
GetConnection();
var response = await _httpClient.GetAsync(new Uri(SnovaHubApiUrls.SnovaHubWebUrl + serviceUrl));
var stringAsync = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var responseJson = stringAsync;
return JsonConvert.DeserializeObject<T>(responseJson);
}
LoggingManager.Error("Received error response: " + stringAsync);
return default(T);
}
catch (Exception exception)
{
LoggingManager.Error(exception);
return default(T);
}
}
#endregion
The issue is that you are setting the HttpClient.BaseAddress and then also passing in a full URL when calling HttpClient.GetAsync(). You need to choose one or the other. So:
Option 1:
private static void GetConnection() {
if (_httpClient == null) {
_httpClient = new HttpClient { BaseAddress = new Uri(SnovaHubApiUrls.SnovaHubWebUrl) }; //You MUST place a / (slash) at the end of your BaseAddress ("http://something.com/api/" for example)
}
}
Then in your GetResultFromApi() method:
...
var response = await _httpClient.GetAsync(serviceUrl); //You MUST NOT place a slash at the beginning of 'serviceUrl' when using BaseAddress
Option 2:
private static void GetConnection() {
if (_httpClient == null) {
_httpClient = new HttpClient(); //Removed BaseAddress
}
}
Then in your GetResultFromApi() method:
...
var response = await _httpClient.GetAsync(new Uri(SnovaHubApiUrls.SnovaHubWebUrl + serviceUrl)); //Passing full URL
Facing an issue while working on ODATA with xml response. Getting internal server error at client side. I debug the code at server side nothing went wrong here, proper response object is generating and returning from server side but "500 internal server" error is generating at client end. Same thing perfectly working fine for when we ask for json response. One more thing I wanted to add here when I hit the url without "$select" proper xml response is generating. Please find below the code for both client and server side.
function ConnectXML()
{
var url = 'https://localhost:321/api/performance?$select=EmployeeID';
$.ajax({
type : "GET",
url : url,
dataType: "xml",
success : function(msg){ alert('Success'); } ,
error : function(msg) { alert('Failed'); }
});
}
public IQueryable<AppraisalsList> GetAppraisals()
{
try
{
string appraisalType = string.Empty;
var allUrlKeyValues = ControllerContext.Request.GetQueryNameValuePairs();
string type = allUrlKeyValues.SingleOrDefault(x => x.Key == "type").Value;
if (!string.IsNullOrEmpty(type) && type.ToLower() != "regular" && type.ToLower() != "ondemand")
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid query params"));
BusinessLogic.Appraisal.Appraisal appraisal = new BusinessLogic.Appraisal.Appraisal(new Settings() { Language = "en-US", UserID = 1, ConnectiongString = "Server=Kazim;Database=BEPMS_BEDemo;Integrated Security=SSPI; MultiSubnetFailover=True;multipleactiveresultsets=True;", AdminConnectiongString = "Server=Kazim;Database=BEPMS_AdminPortal;Integrated Security=SSPI; MultiSubnetFailover=True;multipleactiveresultsets=True;", ApplicationResourcePath = #"D:\Projects\BullseyeEvaluation Performance Management System\BullseyePerformance\Main Project\Source\Binaries", FiscalYearStart = 1, FiscalMonths = 12, DateFormat = "MM/dd/yyyy", NumberFormat = "123,456.78", DecimalPlaces = 2 });
return appraisal.GetAppraisalsList(type).AsQueryable();
}
catch (Exception ex)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError, "Some error occured while processing your request"));
}
}