Ajax Get Request to RestApi - javascript

I'm sure this question has been posted many times before, and I have looked through all related threads. But it's still not working.
We have the JavaScript part:
$.ajax({
type: "GET",
url: "https://localhost:44346/api/persons/",
//dataType: "JSON",
success: function (response) {
callback("a");
},
error: function (response) {
callback("b");
}
}
);
And the C# part:
[Route("persons")]
[HttpGet]
public ActionResult GetPersons()
{
return new JsonResult(new { Success = true, Result = "abc" },
System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
Problem is the Jquery always has error with result = "b". Breakpoints in the Api are hit. I tried with and without dataType: "JSON". Sending parameters to the Api also works, but getting the result back doesnt work. All projects are .Net 5.0.

Replace
url: "https://localhost:44346/api/persons/",
with
url: "https://localhost:44346/api/persons",
and remove [HttpGet] from your action.
[Route("~/api/persons")]
public ActionResult GetPersons()
{
return new JsonResult(new { Success = true, Result = "abc" });
}
But you will stll get error response if APIs CORS is not properly configured.
APIs (not client) startup should be like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors("AllowAnyOrigins");
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

Related

how to call method with variable from javascript

I have this code that is not running in asp.net core 3.1 I need to send a variable to the method GetClientCaseType() it give error in #Model.GetClientCaseType[myInt] myInt if i put 1 or any number it works fine while for variable it give error
function casetype(value)
{
var myInt = parseInt(value.options[value.selectedIndex].value);
var casetype |"= '#Model.GetClientCaseType[myInt]';
alert(casetype + ' = ' + myInt.toString());
$("#ClientCase_cCaseType").val(casetype);
}
in .cs page
public string GetClientCaseType(int? myInt)
{
return something;
}
Any Solution please help thanks in advance
I tried ajax with no result 'error'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebLawyer1.Data;
using WebLawyer1.Models;
namespace WebLawyer1.Pages.ClientCases
{
public class CreateModel : PopulateClientCasePageModel
{
private readonly WebLawyer1.Data.LawyerDbContext _context;
public CreateModel(WebLawyer1.Data.LawyerDbContext context)
{
_context = context;
}
public IActionResult OnGet()
{
PopulateClientInfosDropDownList(_context);
PopulateCaseTypesDropDownList(_context);
return Page();
}
[BindProperty]
public ClientCase ClientCase { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
//if (!ModelState.IsValid)
//{
// return Page();
//}
//_context.ClientInfo.Add(ClientInfo);
//await _context.SaveChangesAsync();
//return RedirectToPage("./Index");
var emptyClientCase = new ClientCase();
if (await TryUpdateModelAsync<ClientCase>(
emptyClientCase,
"clientcase", // Prefix for form value.
s => s.iClientInfoID, s => s.iCaseTypeID, s => s.cCaseType, s => s.cPart,
s => s.iSequence, s => s.cKeyCase, s => s.dDate, s => s.cTitle,
s => s.cNote, s => s.cDetail, s => s.nFees, s => s.lWinFail, s => s.lClosed))
{
_context.ClientCase.Add(emptyClientCase);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
// Select CategoryID if TryUpdateModelAsync fails.
PopulateClientInfosDropDownList(_context, emptyClientCase.iClientInfoID);
PopulateCaseTypesDropDownList(_context, emptyClientCase.iCaseTypeID);
return Page();
}
public ActionResult GetUploadedFile(int id)
{
var result = _context.CaseType.Where(x => x.iCaseTypeID == id).First();
return Json(result.cCaseType);
}
}
}
<script>
function casetype(value) {
var id = parseInt(value.options[value.selectedIndex].value);
$.ajax({
url: '#Url.Action("GetUploadedFile", "Create")',
type: "POST",
data: JSON.stringify(id),
contentType: "application/json",
datatype: "json",
success: function (data) {
if (data != null) {
var vdata = data;
$('#ClientCase_cCaseType').val(vdata.id);
}
}
});
}
</script>
Actually, you can't do this. The reason is that they do not "live" in the same time. Javascript code is available only after C# / Razor is rendered. Refer to this thread.
So, I think you should use ajax here to send a request to access GetClientCaseType() method.
Update:
For how to send a ajax post request, you need to do the below steps:
1.Add the below service in stratup.cs
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
2.Add the AntiForgeryToken to the current page
#Html.AntiForgeryToken();
3.Set the token to request header in ajax
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
This is an example:
Create.cshtml:
#page
#model RazorApp.Pages.ClientCases.CreateModel
#Html.AntiForgeryToken();
<button id="btn" onclick="casetype()">Click</button>
#section scripts{
<script>
function casetype() {
var id = 1;
$.ajax({
url: 'Create?handler=GetUploadedFile',
type: "POST",
data: { id : id },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
if (data != null) {
var vdata = data;
}
}
});
}
</script>
}
Create.cshtml.cs:
public class CreateModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostGetUploadedFile(int id)
{
var result = "AAA";
return new JsonResult(result);
}
}
Note: the pagehandler should be in this format OnPostXxx() or OnGetXxx().
And the url in ajax should like XXX?handler=Xxx.
Result:

ASP.NET MVC redirect to login page after session expires in AJAX

I just learning ASP.NET MVC and newbie in it so I can't find the solution for some problem. Maybe somebody faced this problem and can give me advice? Thanks for all!
In my project, I use ASP.NET Identity for authorization.
The only problem I faced is how to redirect the user to login page after session expires. If action from controller called not from AJAX it works well, but if action called from AJAX function it crashes. I search for the solution, but everything I found not working for me.
Now my code looks like:
Startup.cs
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<ApplicationContext>(ApplicationContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Login"),
LogoutPath = new PathString("/Home/Login"),
ExpireTimeSpan = TimeSpan.FromMinutes(1),
});
}
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="1" />
</authentication>
</system.web>
Function from JS wich calls action:
function click(d) {
//Some logic
$.ajax({
url: '#Url.Action("GetDataForNode", "Home")',
type: 'POST',
dataType: 'json',
cahe: false,
data: { uid: d.id, index: index, nodesUid: nodesUid, request },
success: function (results) {
//Some logic
},
error: function (xhr) {
if (xhr.status === 401) {
window.location.href = xhr.Data.LogOnUrl;
return;
}
}
})
}
And in controller I created:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.Result = new JsonResult
{
Data = new
{
Error = "NotAuthorized",
LogOnUrl = FormsAuthentication.LoginUrl
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
After executed I get this
Add a life cycle method Application_EndRequest handler to your code in global.asax.cs. Every request will end in this method, This method will allows you to redirect to appropriate action, when your request is unauthorized(401) just redirect to appropriate action.
protected void Application_EndRequest()
{
// redirected to the login page.
var context = new HttpContextWrapper(Context);
if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 401)
{
new RedirectResult("~/Account/Login");
}
}
}

Failed to load resource: the server responded with a status of 500 (Internal Server Error) while httpPost

i tried to call C# function through angular
i saw a template how to do it and i got this error.
o tried to look for a solution in google but it is kind pf general problem.
i am pretty sure that i did not adapt my code properly
this is the javascript code:
var app = angular.module("loginApp", []);
app.controller("loginC", ['$scope', '$http',function ($scope, $http) {
$scope.login = function () {
// $http.post('/login.aspx/Login', { userName: $scope.vm.username, password: $scope.vm.password });
var httpreq = {
method: 'POST',
url: 'login.aspx/Login',
data: { userName: $scope.vm.username, password: $scope.vm.password }
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
}]);
this is the C# function declaration(this function reside in login code behind file):
protected void Login(String userName,String password)
{
//some code
}
UPDATE
I changed the HTTP's configuration by adding "headers" to httpreq variable
var httpreq = {
method: 'POST',
url: '/login.aspx/Login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
data: { username: $scope.vm.username, password: $scope.vm.password }
}
$http(httpreq).success(function () {
alert("Saved successfully.");
})
the error is gone and the alert is poped up , but i put BP at the beginning of the function in server side and i still cannot reach there,
i already tried to add [webmethod] and [HttpPost] decorate.
UPDATE2
when i changed the URL to
url: 'login.aspx'
(without the function name) and i set a BP at the PageLoad function ,i succeeded to reach the BP at the server side that mean the problem is with the path to the function.
what can i do?
Try this
var httpreq = {
method: 'POST',
url: '/login.aspx/Login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
data: { userName: $scope.vm.username, password: $scope.vm.password }
}
$http(httpreq).success(function () {
alert("Saved successfully.");
})
[WebMethod]
[HttpPost]
protected static void Login(String userName,String password)
{
//some code
}
you are passing username in small whereas you used in webmethod in camelCase i.e userName. also use static webmethod.

How to make Rest Spring work with JS

Folks
I have a problem with consuming a rest using javascript.
This Rest is already being used in other applications, where PHP and Aspx conserve the same described below.
#Controller
#RequestMapping("/userlogin")
public class UserRest {
#Autowired
private UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<RetornUser> login(#RequestBody User user) {
RetornUser retornUser = new RetornUser();
try {
user = userService.autenticarUsuario(user);
retornUser.setUsuario(usuario);
retornUser.setCodigoRetorno(1);
} catch (Exception e) {
retornUser.setCodigoRetorno(-1);
retornUser.setMensagem(e.getMessage());
}
return new ResponseEntity<>(retornUser, HttpStatus.OK);
}
}
The code above works perfectly with PHP, Aspx and Java calls.
When I call the routine, the JS is falling into the error function before receiving the return.
The worst thing is that the JS error is not bringing the reason. Below the code in pure HTML.
function logar() {
try {
var json = JSON.stringify(usuario);
json = "{\"nome\": \"garra\",\"senha\": \"1234\"}";
$.ajax({
type: "POST",
url: "http://localhost:8080/garrasystem/webservice/userlogin/login",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 300000, // sets timeout to 3 seconds
success: function (retorno) {
alert(retorno);
},
error: function (data, textStatus, xhr) {
alert(data.responseText);
}
});
} catch (e) {
console.log(e);
}
}
The way it is there, when I send debug, it calls the normal login method, but it falls into the error function, nor does it expect the login method to perform the return.
I put the method return String only and nothing too.
My Spring is 4.
I'm waiting for some help
Vinicius Castro
Looks like you are passing string instead of json object. Could you try passing the following:
var data = {
nome: "garra",
senha: "1234"
};
Folks
Being focused on a single problem, I forgot to analyze the button type. It was like type submit, so it was not working. It is like experiencing these kind of mistakes.
Thank you to all who supported me

Call c# function with javascript code

I would like to call a code behind function from the client side.
The function cannot be static - should modified unstatic variabels.
I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn.
How can I send parameters to that code behind function?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
This is the client side to call backend method. The server side to accept this request:
public ActionResult ActionName(string param1)
{
return View(param1);
}
In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters.
Using MVC and jQuery
Client Side ( Using Razor )
$.ajax({
url: '#Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
Server Side
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
Note: HttpGet Verb is the default verb for every ActionResult/JsonResult
the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow :
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}

Categories