I have $get calling un my C#- MVC - Angular Js Proj .
The url for request is incorrect for me and routing to the root proj folder on computer
$http.get('../Home/GetResponse').success(function (response) {
alert(response);
});
How I should write the url given that the my controller name is 'HomeController' and the function is 'GetResponse' ?
Thanks .
Use:
$http.get('Home/GetResponse').success(function (response) {
alert(response);
});
By using $http.get your are making a http request. This request can only be handled by a web server.
You should be hosting your asp.net MVC website in IIS and your $http.get should use an address along the lines of
http://localhost/Home/GetResponse
Right now you are trying to make an http request to a file on your file system which will not work. It would expect to find a folder called Home and a file called GetResponse.
Only IIS is able to load the http modules that can translate the route (in this case /Home/GetResponse) to an action on a controller.
$http.get(baseurl+'Home/GetResponse').success(function (response) {
alert(response);
});
just add baseurl in the layout page as
var baseurl=#Url.Content("~/");
Related
Im creating a ASP.NET Core 3.1 site and have now published a test version to a azure app service.
When I run my web app on localhost it works just fine, but when I run the published app it seems like some of the actions does not exist anymore (I know they exist, otherwise it would be compilation errors) and all I get back is a 404 not found.
An example of a action that goes rouge when I publish is "LogIn" that takes a email and a code and is located in HomeController:
public IActionResult LogIn(string email, string code)
{
//Code
return Json(jObject);
}
This action is called via this Ajax code:
$.ajax({
type: "GET",
url: "/Home/LogIn",
data: { email: email, code: code },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) {
console.log(response);
}
});
The ajax call returns 404 not found on the published app.
But I have also tried to do the same thing by creating a "a" tag:
<a asp-action="LogIn" asp-controller="Home" asp-route-email="test#test.com" asp-route-code="123">Login</a>
But that returns 404 not found as well...
Solutions I have tried:
Added Route value to the action (and the controller):
[Route("Home/LogIn")]
public IActionResult LogIn(string email, string code)
{
//Code
return Json(jObject);
}
Moved the ajax code to the .cshtml file and changed url to:
url: "#Url.Action("LogIn", "Home")"
But none of these solutions solve my problem...
Is there anyone that recognize this problem? Does anyone have a solution for it? I would really appreciate some help.
Thanks in advance!
EDIT:
I have tested to remove all content of the "LogIn" action and replaced it with "return View()" and created a view for it, and it works fine. The "LogIn" action can be found via the ajax call as well, but when I add the code I want there again and publishing, the action gets a 404 not found again...
I then tried to add [HttpGet] to the action and it resulted in a 405 method not allowed. So I think it sees the action but ignore it or something similar.
Here is a diagnostic solution for you.
Since your project works fine on localhost, you could publish as a folder like below, which will give you a folder like the second pic.
Test the project through IIS on your local computer. Actually if the project works well on IIS, it should be well on Azure.(The path is the folder's path you create from step 1)
Compress the content of the publish folder you create from step 1, and drag it to the app service's kudu site like this:
If all the steps above works fine, it means your project is fine. Check your deploy method, and make sure no file lost while depoy.
Tips: If you still cannot sure if file lost or not, you should find the method under bin folder like myproject.dll, and decompile the file, check source code exsit or not.
SOLVED!
I solved the problem.
I was looking at the azure app service log and found this when i did the call:
2020-12-04 19:14:57.864 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Route matched with {action = "LogIn", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult LogIn(System.String, System.String) on controller Project.Controllers.HomeController.
And further down in the log stream this showed up:
2020-12-04 19:14:57.929 +00:00 [Error] Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware: An unhandled exception has occurred while executing the request.System.Data.SqlClient.SqlException (0x80131904): Cannot open server 'mysrvname' requested by the login. Client with IP address 'appserviceIP' is not allowed to access the server.
So the problem was all the actions that made database calls "was not found" but they actually got sqlexecptions beacuse i forgot to update my server firewall rules to accept my app services IP adress.
Really wierd that I got a 404 not found when I should get some server error...
I'm working on a ASP.NET MVC app where we have a requirement to produce PDF reports. The generation of these PDF reports on the back-end can take a long time (over 30 seconds). Our company uses a proxy called squid which will timeout any HTTP requests taking more than 30 seconds.
Because of the above, requesting a pdf report directly via a link or a get request will timeout.
How do I get around this? Is there a way to deliver files asynchronously? Or do I have to use a more elaborate protocol where the client requests the files and then polls the server at regular intervals to see if the file has been produced, before requesting it again for download when ready?
You could use something like signalr to poll the server for job completion and then redirect the browser once it's complete.
Just an idea but you could use hangfire, to schedule the pdf creation.
I found some useful help in an existing question Handle file download from ajax post
Here's what I did. I created an ajaxDownload css class to identify links that I want to be handled asynchronously.
I created a method on the server called DownloadFile that will download the file from a specific location.
I replaced the original url that was returning the file with a url that generates the PDF and then return its file name. I pass on the filename in the success event and then use window.location.href to download the file.
$("a.ajaxDownload").on("click", "", function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
type: "POST",
url: url,
error: function(res) {
alert("an error has occured");
},
success: function(res) {
var url2 = '/QuoteSummary/DownloadFile/?filename=' + res;
window.location.href = url2;
}});
});
In Visual Studio 2015 I have 2 projects in my solution: ASP.NET MVC app and an ASP.NET Web API app. The MVC app uses a different port in IIS express than the Web API app.
In the debugger I see that I end up in the ChangeName method Web API controller, but the parameter never gets set and then in the console I see errors. The errors have to do with cross domain problems.
Is it this complicated to make a jQuery AJAX request to a different domain? When I use fiddler everything works fine.
The domain for the app that the below code is in is: localhost:50675 and I am trying to make a request to another project in the same solution that is localhost:27081
Here is my AJAX request:
$("#btnChangeName").click(function() {
var name = $("#Name").val();
var url = 'http://localhost:27081/api/products/changename';
$.ajax({
url: url,
type: 'POST',
dataType: 'text',
data: JSON.stringify({name: name}),
success: successFuncApi,
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
Here is one of the errors I am seeing in the console:
XMLHttpRequest cannot load http://localhost:27081/api/products/changename.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:50675' is therefore not allowed access.
The response had HTTP status code 500.
I am not sure if the error is due to my controller erroring since the param is null or if it is the root of my problem.
The Error occurs because you send a request from origin (source) to another one.
all you need to do is to enable cross origin in your backend (or your ASP.NET Web API) to be added in the header.
this link will give you more information, and guide you to enable cross-origin requests.
This error might go away, when you move your apps to production (depending on the setup of webservers). As for now, I would try something, as explained here Enabling Cross-Origin Requests in ASP.NET. If this doesn't fit your situation, there are other ways to enable the same thing.
You could also deploy your apps on IIS. Create app for client, then add new app to that app for webapi.
I'm now trying to build a web service based on MVC 4 and client using HTML. The problem is my HTML file is put outside the application and my MVC service is running on Visual Studio IIS Express. I don't know if it causes my problem or because of any missing anything in Web.config.
Here is my code of Index method inside my Controller:
public ActionResult Index() {
return Content("It works");
}
And this is my code in client side:
$.ajax({
url: 'http://localhost:54502/<MyControllerName>/Index',
type: 'POST',
datatype:"JSON",
contentType:"application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function(data) {
alert("error");
},
complete: function(jqXHR,status) {
}
});
The problem is it always alert out "error" and nothing seems to work. Any help would be highly appriciated!
The content isn't serialised as JSON. If it is HTML it is going to be of content-type text/html rather than application/json.
I'd recommend using WebAPI or WCF's WebHttpBinding for this.
I figured out my solution and it related to Cross-Domain problem. I use WebAPI and install CORS package using NuGet and now I can access the web service via ajax call even outside my localhost domain.
I have a Web API written in ASP.NET that I'm consuming via AngularJS $http.
I have enabled caching in my AngularJS factory as follows but every request still returns a response of 200, never 200 (from cache) or 304 (and by every request I mean making the same web api request numerous times on the same page, revisiting a page I've already visited that contains a Web API request, refreshing said page etc).
angular.module('mapModule')
.factory('GoogleMapService', ['$http', function ($http) {
var googleMapService = {
getTags: function () {
// $http returns a promise, which has a 'then' function, which also returns a promise
return $http({ cache: true, dataType: 'json', url: '/api/map/GetTags', method: 'GET', data: '' })
.then(function (response) {
return response.data;
});
};
return googleMapService;
}]);
Am I missing something from the AngularJS side of things? Or is this a Web API problem. Or both?
Turns out it was a Web API thing. I'd overlooked the fact that the response header clearly stated that caching was disabled.
Response as viewed in the Network tab of Google Chrome:
Upon further investigation (and as seen in the image above), caching is disabled in Web API controllers. Even the [OutputCache] attribute, which is used in regular MVC controllers, isn't supported.
Luckily I found this blog:
http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/
which lead me to these two solutions:
ASP.NET Web API CacheOutput
CacheCow
I decided to go with CacheOutput as it lets me use attributes like:
[CacheOutputUntilToday] which supports server & client side caching.
Or if I wanted to just use client-side caching I can use something like:
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 0)]
Which seemed a little easier at first glance that CacheCow's approach. And easier to refactor out later if need be.
Now additional requests give me a 200 (from cache):
With a refresh giving me a 304 Not Modified:
Problem solved! Hope this helps someone else.