I have implemented one MVC application with Basic implementation as per this
Now when I call this action method from my Webform application using AJAX, it did not asking for credentials and throwing an 401 error.
This is my ajax function:
function testSS()
{
$.ajax({
url: 'http://localhost:52099/Controller/Sample',
type: 'GET',
success: function (result) {
$("#ctl00_cphPageContent_SSlbl12").val(result);
},
error: function (xhr) {
alert(xhr);
}
});
}
How can I call authenticated method from webform project?
Thanks!
In order to make this work, you need to add an Authorization header, containing base64-encoded login and password.
To encode base 64, you can use btoa()
var authHeader = window.btoa("login:password");
Now, you can add this header (see $.ajax documentation)
$.ajax({
url: 'http://localhost:52099/Controller/Sample',
headers: { Authorization: authHeader },
type: 'GET',
success: function (result) {
$("#ctl00_cphPageContent_SSlbl12").val(result);
},
error: function (xhr) {
alert(xhr);
}
});
Please note this will not be very secure, because login/password are known from the client, and sent in an easily readable way, so very easy to be found by an attacker.
If the webform page and MVC action are in the same project, and the user is ogged on your website, you should probably use the asp.net [Authorize] attribute instead : it will check the auth cookie, and not rely on a login/password, it's much more secure.
Related
In laravel or some express.js libs add middleware to check if a field is given called _Method which will override the actual http method of the http request on arrival of the server, because the browser only supports POST and GET.
Does ASP.NET (.NET Framework) contain a build-in middleware like those I just mentioned, I couldn't find anything online.
If so, how do I use it or do you know such an atricle.
If not, how can I create such a middleware myself.
I could not create one myself, because the HttpRequest in the HttpContext is readonly and the HttpMethod in the HttpRequest is readonly aswell.
Or is the only choice to use preventDefault() and/or ajax to send (for example) a DELETE request via javascript?
First of all, you need to assign [HttpDelete] attribute to your function in the controller or API. for example:
[HttpDelete]
public JsonResult MyDeleteFunction(int id)
{
//Write your delete code here
return Json("some responses");
}
Then in client-side, you can use ajax to do the delete request.
$.ajax({
url: '/ControllerName/MyDeleteFunction',
dataType: "json",
type: "DELETE",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({id: 123}),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data);
},
error: function (xhr) {
alert('error');
}
});
After some digging, I found that later in the chain of ASP.NET the HttpContext Changes into HttpContextBase. This context contains GetHttpMethodOverride().
I looked the Method up on github, because it's open source and ASP.NET does contain a middleware such as mentioned.
You can override the actual http method using the key X-HTTP-Method-Override in either the Header, Form or Query string and the actual http method must be POST for the middleware to even consider a http method override.
I am developing my first web app using angularjs , created a aspx page , added the controller. When I debug in local ASPX page is getting opened and Controller also working fine , but when I call the save function in angular . It is returning the status code as not authorized .
below is the call i have made
$http({
method: "POST",
url: "Login.aspx/SaveOrganizationName",
dataType: 'json',
data: { },
headers: { "Content-Type": "application/json" }
}).
Any suggestion, how to fix ?? I have set the project to run on IIS. as I'm not having enough idea on this , please explain me detailed
thanks
So I have this application that´s almost finished but i need to add now some extra security and since i am not too familiar with some of Asp.Net mvc 5 methods I have this question.
Is it possible to add some sort of encryption or something similar to a jsonresult? The idea is if I have sensitive information being sent through json is there anything I can add server side to secure it or does MVC5 take care of that already?
here is a very basic example
$.ajax({
type: "POST",
url: 'GetImptInfo',
data: { 'Something': Something, 'Something2': Something2}, //this can be anything
dataType: "json",
success: function (result) {
alert('Added');
//do stuff
},
error: function (xhr, ajaxOptions, thrownError) {
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
the controller method
public JsonResult GetImptInfo(int Something, int Something)
{
//get stuff from the server
var imptInfo = RequestInfo();
return Json(impInfo, JsonRequestBehavior.AllowGet);
}
Is there anything I can add in order to secure that json or is what I have enough?
You can use a secured protocol to transport your information i.e https. You can also have a look at this link to see why JsonResult is needed:
Why is JsonRequestBehavior needed?
I have a C# .NET MVC 5 project. I'm trying to submit a GET request from ajax to a controller method on the server. The problem is that, even though this jquery is being called, the GET always returns a 404. Here is the js:
var theArguments = { "prefix": prefix, "level": level, "number": number };
$.ajax({
url: "GetMasteryObjective",
type: "GET",
data: theArguments,
//data: JSON.stringify({ prefix: "prefix", level: "level", number: "number" }),
//url: "/MasteryObjectiveAPI/GetMasteryObjective?prefix=" + prefix + "&level=" + level + "&number=" + number,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Successfully queried the database to validate the given mastery objective.");
},
error: function () {
console.log("There was an error with trying to validate the mastery objective with the database.");
}
});
As you can see I've tried several variants of how the variables are submitted (commented out). This is the controller method that is never getting hit.
[HttpGet]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static MasteryObjective GetMasteryObjective(String prefix, String level, String number)
{
//code here
}
Other methods in the same controller have no problem being posted to. So maybe there's something I don't understand about GET? I understand that it should be valid to submit variables with a GET request.
Wow. I just discovered the answer to my own question while creating this post. I needed to remove static from my controller method.
Happy that, you have got the solution.
However, thinking that this may help others .....
One of the reason for ajax call not hitting the Method in controller is:
If the controller method is under [Authorize] but the user is trying to hit without logging in.
Solution: If want to allow unauthorized access to that method; mark that method has [AllowAnonymous], otherwise log-in and then try.
I tried all my efforts, but just can't understand where the error lies. I searched the google also but did not find any good solution. It is not actually calling the controller/action in mvc. The same is running good in the other parts of the project.
I have a contrller "RB" under a folder "MVC", the action is defined as "SS".
and I am firing following code from my javascript file :
var sSch = function (request, response) {
var t = request.RF.substring(0, 1);
var d = new Date(request.RNR);
$.ajax({
url: "/MVC/RB/SS",
type: "POST",
dataType: "json",
data: {
_rId: request.ReportId,
_date: d.toString(),
_fcy: t
},
success: function (data) {
alert('Success');
},
error: function (data) {
alert('Error');
}
});
};
I am calling this function onClick of a button and properly getting the values in Request variable, but it is not anyhow calling the Controller/Action there.
On firebug I tested it throws the exception "ReferenceError: url is not defined". I am using MVC3 under VS 2010.
Please Help.
You have to define your action properly instead of
url: "/MVC/RB/SS",
use
url: #Url.Action("SS", "RB")
For the url you have 'MVC/RB/SS' this is relative to your current directory a quick test would be to put in url: "../MVC/RB/SS" or url: "../../MVC/RB/SS" depending on how deep you page is in the site structure.
Another way would be to try this:
url: "#Action("/MVC/RB/SS")",
this will create the correct url at the correct level for you and should be picked up.
Try this:
url: "~/MVC/RB/SS",
This will resolve to path "http://site-name/MVC/RB/SS".
What does Firebug say?