I am currently working on an ASP.NET MVC site and I am having trouble with ajax posts in my release build. The site has two database connections, one to a "dummy" server that allows me to test code without affecting the live server. So, I had to configure the site to point to the live server for the release configuration, and the dummy server for the debug configuration.
Everything other than the database connection is the same, but for some reason my ajax call works fine on the debug build but throws an error on the release build. I get an ERROR THROWN: Not found alert on the ajax failure, but it only fails in the release build.
My call to the controller method looks like this:
$.ajax({
type: "GET",
url: "#Url.Action("ReleasePlotFieldName", "TestRecord")" + '?fieldName=' + x + '&fileName=' + filename,
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
alert("success");
for (var key in data) {
let b = {
name: data[key][0],
value: data[key][1],
line: data[key][2],
arc: data[key][3]
};
chartData.push(b);
}
PlotData();
//the parameter data contains the array returned from the json PlotFieldName function
},
error: function (xhr, textStatus, errorThrown) {
alert('STATUS: ' + textStatus + '\nERROR THROWN: ' + errorThrown);
}
and the controller method looks like this:
[HttpPost]
public JsonResult ReleasePlotFieldName(string fieldName, string fileName)
{
var spiData = (DataDecoder)Session["dataDecode"];
var selectedItem = fieldName;
spiData.DecodeData(selectedItem);
List<float[]> toPlot = spiData.returnPlotVector();
return new JsonResult()
{
Data = toPlot,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = int.MaxValue // Use this value to set your maximum size for all of your Requests
};
}
I have absolutely no clue why the release build is not executing as expected (as the debug build is doing). I welcome any and all suggestions.
Here is the network tab of the browser when the call is made
Your controller action is decorated with a [HttpPost] attribute but your jquery .ajax() request is a GET. Change one or the other depending on your use case (looks like GET could be more appropriate).
I am trying to call a Webmethod by ajax call.The webmethod has been implemented in to a .asmx file.When I publish the project and deploy in my local server IIS. Then the webmethod successfully executed from my local IIS .But when I deploy the same published version into different server IIS and try to access the Webmethod then I am getting "500 Internal Server Error".
I Cannot not understand why the same code behaving different.What mistake I am doing please suggest.
The code has been written as follows -
Code in .cshtml file
$.ajax({
type: "POST",
url: "/Root/Shared/CommonServices.asmx/SubmitRequestInterface2",
data:
{ 'fromDate': $("#txtBeginData").val(),
'toDate':$("#txtEndDate").val()
},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (res) {
alert(res.children[0].innerHTML);
}
});
Code in CommonServices.asmx
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string SubmitRequestInterface2(string fromDate, string toDate)
{
try
{
//string fromDate =
Convert.ToString(System.Web.HttpContext.Current.Request.Params["fromDate"]);
//string toDate =
Convert.ToString(System.Web.HttpContext.Current.Request.Params["toDate"]);
ClsProcess objProcess = new ClsProcess();
objProcess.Process(fromDate, toDate);
}
catch (Exception ex)
{
throw;
}
return "Hello World";
}
Thanks
I've integrated the Charisma V.2.0.0 bundle in an ASP.Net C# application. All looks good until I write an .ajax call to a web service. Ajax call, a standard format, works in a basic asp.net page, but from the bundle. It seems like something in his 'bower_components'. I removed reference to bower_components/jquery and am including ajax.googleapis.com... 3.3.1.
Does anyone have experience with this problem? and what might be a solution? I like the UI Muhammad designed and would like to keep developing which is platform.
The axax call looks like this:
// Edit Client button
$(document).on("click", "[id*=btnEditClient]", function () {
// Edit selected client/Event Id - get data from Ajax
//alert($(this).val());
var clientId = $(this).val();
var clientInfo = JSON.stringify({ clientId: clientId });
alert(clientInfo);
$.ajax(
{
url: '<%= ResolveUrl("QRWebService.aspx/GetClientListService") %>',
type: "POST",
data: clientInfo,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// results
alert(result.d);
alert('no error ' + JSON.stringify(result));
$("#myModal").modal()
return true;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error: ' + textStatus);
}
});
return false;
})
and the result is 'undefined' where the web service never gets called.
The web serivce is:
[WebMethod]
public static DataSet GetClientListService()
{
// returns dataset LIST of Client Id and Name
DataSet ds = new DataSet();
SQLHelper.SqlQuery oQuery = new SQLHelper.SqlQuery();
String strSQL;
try
{
strSQL = "SELECT Clients.ClientId, ClientName FROM Clients ";
strSQL += "WHERE ClientActive=#clientActive";
ds = oQuery.GetDataSet(strSQL);
} catch(Exception ex){
errorMessage = ex.Message;
}
return ds;
} // end GetClientEventList()
Post ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)". Changing the App_Start from Permanent to:
settings.AutoRedirectMode = RedirectMode.Off;
did the trick. I hope this helps others. Thank you StackOverflow and all those who post solutions to tricky issues.
I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.
I've been working through a simple API example, a modified version of the ServiceStack Hello World example with authentication. The goal of the proof of concept is to create an a RESTful API that contains services requiring authentication accessible entirely through Ajax from several different web projects.
I've read the wiki for, and implemented, Authentication and authorization and implementing CORS (many, results [sorry, not enough cred to point to the relevant link]). At this point, my Hello service can authenticate using a custom authentication mechanism which is over-riding CredentialsAuthProvider and a custom user session object. I've created, or borrowed, rather, a simple test application (an entirely separate project to simulate our needs) and can authenticate and then call into the Hello service, passing a name, and receive a 'Hello Fred' response through a single browser session. That is, I can call the /auth/credentials path in the url, passing the username and id, and receive a proper response. I can then update the url to /hello/fred and receive a valid response.
My breakdown in understanding is how to implement the authentication for all ajax calls. My initial login, below, works fine. No matter what I do, my attempt to call the authenticated service via ajax, I either receive a OPTIONS 404 error or Not Found error, or Origin http // localhost:12345 (pseudo-link) is not allowed by Access-Control-Allow-Origin, etc.
Do I need to go this route?
Sorry if this is confusing. I can provide greater details if required, but think this might be sufficient help the knowledgeable to help my lack of understanding.
function InvokeLogin() {
var Basic = new Object();
Basic.UserName = "MyUser";
Basic.password = "MyPass";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(Basic),
url: "http://localhost:58795/auth/credentials",
success: function (data, textStatus, jqXHR) {
alert('Authenticated! Now you can run Hello Service.');
},
error: function(xhr, textStatus, errorThrown) {
var data = $.parseJSON(xhr.responseText);
if (data === null)
alert(textStatus + " HttpCode:" + xhr.status);
else
alert("ERROR: " + data.ResponseStatus.Message + (data.ResponseStatus.StackTrace ? " \r\n Stack:" + data.ResponseStatus.StackTrace : ""));
}
});
}
EDIT:
Based on the responses and the link provided by Stefan, I've made a couple of changes:
My Config (Note: I'm using custom authentication and session object and that is all working correctly.)
public override void Configure(Funq.Container container)
{
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new CustomCredentialsAuthProvider(),
}));
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders = {
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
{ "Access-Control-Allow-Headers", "Content-Type, Authorization" },
},
DefaultContentType = "application/json"
});
Plugins.Add(new CorsFeature());
this.RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpReq.HttpMethod == "OPTIONS")
httpRes.EndRequest(); // extension method
});
Routes
.Add<Hello>("/Hello", "GET, OPTIONS");
container.Register<ICacheClient>(new MemoryCacheClient());
var userRep = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRep);
}
My Simple Hello Service
[EnableCors]
public class HelloService : IService
{
[Authenticate]
public object GET(Hello request)
{
Looks strange when the name is null so we replace with a generic name.
var name = request.Name ?? "John Doe";
return new HelloResponse { Result = "Hello, " + name };
}
}
After making the login call, above, my subsequent call the Hello service is now yielding a 401 error, which is progress, though not where I need to be. (The Jquery.support.cors= true is set in my script file.)
function helloService() {
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "json",
url: "http://localhost:58795/hello",
success: function (data, textStatus, jqXHR) {
alert(data.Result);
},
error: function (xhr, textStatus, errorThrown) {
var data = $.parseJSON(xhr.responseText);
if (data === null)
alert(textStatus + " HttpCode:" + xhr.status);
else
alert("ERROR: " + data.ResponseStatus.Message +
(data.ResponseStatus.StackTrace ? " \r\n Stack:" + data.ResponseStatus.StackTrace : ""));
}
});
}
Again, this works in the RESTConsole if I first make the call to /auth/credentials properly and then follow that up with a call to /hello.
FINAL EDIT
Following Stefan's advise, below, including many other links, I was finally able to get this working. In addition to Stefan's code, I had to make one additional modification:
Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization"));
On to the next challenge: Updating Jonas Eriksson's CustomAuthenticateAttibute code (which appears to be using an older version of ServiceStack as a couple of functions are no longer available.
THANKS AGAIN STEFAN!!
this code works for me, based on the Wiki documentation Custom authentication and authorization
Code is based also in the blog post from Community Resources
CORS BasicAuth on ServiceStack with custom authentication
For Basic Authentication, a custom provider
public class myAuthProvider : BasicAuthProvider
{
public myAuthProvider() : base() { }
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
//Add here your custom auth logic (database calls etc)
//Return true if credentials are valid, otherwise false
if (userName == "admin" && password == "test")
return true;
else
return false;
}
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
//Fill the IAuthSession with data which you want to retrieve in the app
// the base AuthUserSession properties e.g
session.FirstName = "It's me";
//...
// derived CustomUserSession properties e.g
if(session is CustomUserSession)
((CustomUserSession) session).MyData = "It's me";
//...
//Important: You need to save the session!
authService.SaveSession(session, SessionExpiry);
}
}
public class CustomUserSession : AuthUserSession
{
public string MyData { get; set; }
}
In AppHost
using System.Web;
using ServiceStack; // v.3.9.60 httpExtensions methods, before in ServiceStack.WebHost.Endpoints.Extensions;
using ....
AppHost.Configure
public override void Configure(Container container)
{
SetConfig(new ServiceStack.WebHost.Endpoints.EndpointHostConfig
{
DefaultContentType = ContentType.Json
..
// remove GlobalResponseHeaders because CordFeature adds the CORS headers to Config.GlobalResponseHeaders
});
Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization")); //Registers global CORS Headers
this.RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
if (httpReq.HttpMethod == "OPTIONS")
httpRes.EndRequestWithNoContent(); // v 3.9.60 httpExtensions method before httpRes.EndServiceStackRequest();
});
//Register all Authentication methods you want to enable for this web app.
Plugins.Add(new AuthFeature(() => new CustomUserSession(), // OR the AuthUserSession
new IAuthProvider[] {
new myAuthProvider(),
}) { HtmlRedirect = null }); // Redirect on fail
HtmlRedirect answer
Routes.Add<TestRequest>("/TestAPI/{Id}", "POST,GET, OPTIONS");
....
}
In Service
[Authenticate]
public class TestAPI : Service
{
...
}
in javascript
jQuery.support.cors = true;
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
Login first
function Authenticate() {
$.ajax({
type: 'Post',
contentType: 'application/json',
url: serverIP + 'Auth',
cache: false,
async: false,
data: {},
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", make_base_auth(username, password));
},
success: function (response, status, xhr) {
localStorage.sessionId = data.SessionId;
var UserName = response.userName;
},
error: function (xhr, err) {
alert(err);
}
});
}
and request
function DoTest() {
var TestRequest = new Object();
TestRequest.name = "Harry Potter";
TestRequest.Id = 33;
var username = "admin";
var password = "test";
$.ajax({
type: 'Post',
contentType: 'application/json',
cache: false,
async: false,
url: serverIP + '/TestAPI/'+ TestRequest.Id,
data: JSON.stringify(TestRequest),
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Session-Id", localStorage.sessionId);
},
success: function (response, status, xhr) {
var s= response.message;
},
error: function (xhr, err) {
alert(xhr.statusText);
}
});
}
these questions here and here are helpful.
Also this answer for CredentialsAuthProvider, in case we can use cookies and sessions.