i'm developing an MVC4 application and using Web API for my web services to send data for android application and i need some testing on the results so when i use GET Request Method i put in the browser this URL
http://localhost:2100/api/Accounts/LogIn?UserName=Fadi&PassWord=123456
this is my method
[HttpGet]
public ConfrmationMessage LogIn(string UserName, string PassWord)
{
ConfrmationMessage flag = new ConfrmationMessage();
if (WebSecurity.Login(UserName, PassWord))
{
flag.status = "LogedIn";
return flag;
}
else
{
flag.status = "The user name or password provided is incorrect.";
return flag;
}
}
and every thing work fine but when i'm using an [HttpPost] and use this URL again
http://localhost:2100/api/Accounts/LogIn?UserName=Fadi&PassWord=123456
it give me this error
{"Message":"The requested resource does not support http method 'GET'."}
so i did do some search and find that the post method use anther way to put data from URL link but still can not understand how to write the correct URL for the post method so any help and thanks in advance.
you submit a post request via a form element like so (there are more attributes you can add but you can look these up easily.
<form action="~/api/Accounts/LogIn" method="POST">
<!--input elements here -->
</form>
or through an ajax call (requires jquery)
$.ajax({
url: "~/api/Accounts/LogIn",
type: "POST",
data: { UserName: "Fadi", PassWord: "123456" }
success: function(result) {
//do something when response is successful (result is the response)
},
error: function(jqXHR, textStatus, errorThrown) {
//will return exception info from server
//jqXHR is the request in xml format
//textStatus is the description of the exception (if there is one)
//errorThrown is the excception object thrown (if there is one)
}
});
Related
I working on mvc asp.net project. I call my controller function with ajax, the call status is 200 but it is not successful, and goes to error section.
service:
public async Task<IEnumerable<TeamDto>> GetAllTeamsList()
{
var teams = await _teamRepository.GetAll().Include(u => u.Users).ThenInclude(m => m.User).ToListAsync();
return ObjectMapper.Map<IEnumerable<TeamDto>>(teams);
}
Controller:
public async Task<IEnumerable<TeamDto>> GetTeams()
{
var teams = await _teamAppService.GetAllTeamsList();
return teams;
}
js file:
$.ajax(
{
type: "GET",
url: "/App/Team/GetTeams",
success: function (data) {
///
},
error: function (data) { console.log("it went bad " + JSON.stringify(data)); }
});
Error:
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
this is what I get when copy the url in the browser:
{"result":[{"tenantId":1,"name":"admin
team","users":[{"tenantId":1,"userId":2,"teamId":58,"user":{"profilePictureId":null,"shouldChangePasswordOnNextLogin":false,"signInTokenExpireTimeUtc":null,"signInToken":null,"googleAuthenticatorKey":null,"pin":"1234","hourlyRate":0.00,"payrollId":"","warehouseId":1,"tandaUser":null,"normalizedUserName":"ADMIN","normalizedEmailAddress":"ADMIN#DEFAULTTENANT.COM","concurrencyStamp":"bd7ee91e-587b-4ae2-bc97-be2ce7d7789b","tokens":null,"deleterUser":null,"creatorUser":null,"lastModifierUser":null,"authenticationSource":null,"userName":"admin","tenantId":1,"emailAddress":"admin#defaulttenant.com","name":"admin","surname":"admin","fullName":"admin
admin","password":"AQAAAAEAACcQAAAAENfcSE+zBppFKVxKUynGBiy4WZgDU3C3gbbWnQUdEyBb5J/S0uLkcqk+2MwM0DXxjw==","emailConfirmationCode":null,"passwordResetCode":null,"lockoutEndDateUtc":null,"accessFailedCount":1,"isLockoutEnabled":true,"phoneNumber":"","isPhoneNumberConfirmed":false,"securityStamp":"07a4d582-7233-3fbc-f3f7-39f015ee388b","isTwoFactorEnabled":false,"logins":null,"roles":null,"claims":null,"permissions":null,"settings":null,"isEmailConfirmed":true,"isActive":true,"isDeleted":false,"deleterUserId":null,"deletionTime":null,"lastModificationTime":"2020-09-30T02:54:34.402372Z","lastModifierUserId":null,"creationTime":"2019-09-05T23:27:47.8514365Z","creatorUserId":null,"id":2},"team":{"tenantId":1,"name":"admin
team","users":[
Open up the developer tools and look at the URL it is trying to request. Normally in the context of the application, you don't have the /App defined. In fact, you can use ASP.NET MVC Url helper to get the action method, to make sure the path is correct:
$.ajax({
type: "GET",
url: "#Url.Action("GetTeams", "Team")",
Also, normally you would return data via JSON from the controller like:
public async Task<IEnumerable<TeamDto>> GetTeams()
{
var teams = await _teamAppService.GetAllTeamsList();
return Json(teams, JsonRequestBehavior.AllowGet);
}
And maybe that would make a difference, using Json() from the asp.net mvc controller. Note AllowGet ensures that GET requests on an action returning JSON works, otherwise it will be blocked and return an error.
I am new to mobile development. My project is build using asp.net. For authentication I am using build it UserManager & User.Identity.
I have bunch of existing web apis and I wish to use them from mobile app.
I know , I could pass a secret hash to web api after authenticating, but that would involve a huge code refactoring.
I been wondering if there other ways to handle authentication & authorization with nativescript & asp.net .
Do you know any useful resources for this topic?
Many thanks for your help!
It depends quite heavily on your API structure, but I would recommend somethign like this:
Firstly you would need to use the Nativescript Http module. An implementation to get a an HTTP GET calls returned header might look like this:
http.request({ url: "https://httpbin.org/get", method: "GET" }).then(function (response) {
//// Argument (response) is HttpResponse!
//for (var header in response.headers) {
// console.log(header + ":" + response.headers[header]);
//}
}, function (e) {
//// Argument (e) is Error!
});
So your backend might return a JSON Web Token as a header. In which case on the success callback you would probably want to store your token in the applications persistent memory. I would use the Application Settings module, which would look something like:
var appSettings = require("application-settings");
appSettings.setString("storedToken", tokenValue);
Then before you make an API call for a new token you can check if there is a stored value:
var tokenValue = appSettings.getString("storedToken");
if (tokenValue === undefined {
//do API call
}
Then with your token, you would want to make an API call, e.g. this POST and add the token as a header:
http.request({
url: "https://httpbin.org/post",
method: "POST",
headers: { "Content-Type": "application/json", "Auth": tokenValue },
content: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
}).then(function (response) {
// result = response.content.toJSON();
// console.log(result);
}, function (e) {
// console.log("Error occurred " + e);
});
Your backend would need to check the Auth header and validate the JWT to decide whether to accept or reject the call.
Alternatively, there some nice plugins for various Backends-as-a-Service, e.g. Azure and Firebase
I have following scenario.
Route Config:
routes.MapRoute(
name: "SellerRegistration",
url: "Registration/{action}/{id}",
defaults: new { controller = "SellerRegistration", action = "Seller", id = UrlParameter.Optional, area = "" },
namespaces: new[] { "MyCompany.Controllers" }
);
So when the url is www.example.com/Registration/Seller, the above route will match and displaying the view without any issues.
class SellerRegistration
{
public ActionResult Seller()
{
return View("Seller");
}
[AjaxOnly]
public bool ValidateUserEmail(string email)
{
return _userService.ValidateUserEmail(email);
}
}
Inside my view Seller.cshtml, I'm trying to make an ajax call to the method ValidateUserEmail().
I'm making ajax call as below:
$.ajax({
type: "POST",
url: rootUrl + "/SellerRegistration/ValidateUserEmail",
cache: false,
async: false,
data: { email: $("#Email").val() },
success: function (data) {
if (data === 'True') {
//redirect to login page
window.location.href = newUrl;
} else {
$("#otherDetails").show();
$("#emailValidation").hide();
$("#submitCompleteFormDiv").show();
}
},
error: function (data, jqXhr) {
console.log(jqXhr.status);
}
});
I have also tried generating url as below in the above ajax method.
url: '#Url.Action("SellerRegistration", "ValidateUserEmail")'
But I'm getting
401 - Unauthorised error.
I'm guessing that I'm not able to make ajax call because of the routing I configured. But, that routing is required to meet other scenarios in the application.
When ajax call is made, the url format is like www.example.com/Registration/Seller
So browser initiates an ajax call to the ValidateUserEmail method inside the controller SellerRegistration from www.example.com/Registration/Seller.
Because there is no real controller named Registration, when the ajax call is made to ValidateUserEmail() inside SellerRegistration controller, I'm getting 401 Unauthorized error.
Can someone please suggest if there is any technique or workaround to make it possible.
Thank you.
I am working in ASP.Net MVC. I have following Javascript code in which i am calling a controller-method which returns a view. I want to send parameters to a controller method which re
function fun(p1,p2)
{
// code here to call controller method which returns view
}
public ActionResult ProblemDetails(p1,p2)
{
// here goes some code.
return View();
}
Please tell me the code which can be used to call controller and send parameters too.
Action Method
public ActionResult SendStream(string a, string b)
{
}
JQuery/JSON
Please note that Get Verb will not support complex Data parameters due to it's Query string length constraint. So use POST Verb instead of GET Verb while sending large data
$.ajax({
url: url,
data: JSON.stringify({ a: "a", b: "b" }), //Two String Parameters
type: 'GET', //For Submit, use POST
contentType: 'application/json, charset=utf-8',
dataType: 'json'
}).done(function (data) {
//Success Callback
}).fail(function (data) {
//Failed Callback
}).always(function(data) {
//Request completed Callback
});
Are you perhaps looking to return a Partial View? You can use jQuery ajax to post to a controller method that returns a Partial View (html). You can then render that HTML on the page.
http://mazharkaunain.blogspot.com/2011/04/aspnet-mvc-render-partial-view-using.html
jQuery.get is the shorthand way to achieve this.
function fun(p1,p2)
{
var url = '/controller/ProblemDetails?p1=' + p1 + '&p2=' + p2;
$.get(url, function (data) {
// data will be your response as html
});
}
I might also suggest to have the action return PartialView() instead of View() since you will not return the layout along with the response. It all depends on your intentions for the returned html.
There are several ways to do it.
For example Ajax:
Quick note first: Make sure that in your MVC routing configuration you have a route configured to reflect the following url below:
function fun(p1,p2)
{
var url = '/ControllerName/ProblemDetails?p1=p1&p2=p2' //url to your action method
$.ajax({
url:url,
type:'post' or 'get', //(depending on how you're doing this. If post you can pass data internally instead of query string ),
dataType:'html', //(for example)
success:function(data){
//data here will contain your View info so you can append it do div for example. You can use JQuery .html() function for that
error: function (xhr) {
//catch error
}
}
})
}
Another way, in case if you want to load your View data to DIV is to use JQUery functions such as .load();
function fun(p1,p2)
{
var url = '/ControllerName/ProblemDetails?p1=p1&p2=p2';
$('#YourDivTagForExample').load(url);
}
$.ajax call can also be abbriviated to $.get, $.post or $.getJSON depending on what kind of a call you want to make to your action method. There is a lot more to it too.
Finally make sure to take a look at this answer. Your question was actually already answered in full:
Correct way to handle Ajax calls in ASP.Net MVC 3
Use JSONResult instead of ActionResult and Manipulate return data in javascript.
I am developing a ASP.Net Web API application and I have used AuthorizeAttribute for the authentication. When the authentication fails, the code that executes is this.
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
This code results to display a Unauthorized request page from the browser but what I want is to display a custom page which I have designed. How do I do that?
Check this out: http://weblogs.asp.net/jgalloway/archive/2012/03/23/asp-net-web-api-screencast-series-part-6-authorization.aspx
What it basically says, you have to check the result code on the client side, and in case it is 401 (Unauthorized), redirect the user to the custom page you've designed:
$(function () {
$("#getCommentsFormsAuth").click(function () {
viewModel.comments([]);
$.ajax({ url: "/api/comments",
accepts: "application/json",
cache: false,
statusCode: {
200: function(data) {
viewModel.comments(data);
},
401: function(jqXHR, textStatus, errorThrown) {
self.location = '/Account/Login/';
}
}
});
});
});
I don't think you can redirect to your custom page from within HandleUnathorizedRequest if you are using WebApi. The code result displays Unauthorized request page because that is how your browser responds to 403 code. WebApi works on HttpMessage exchange and by default uses either Json or Xml media type. If you want to return your customized page as text/html then you will have to write your own media formatter as explained here: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters.