- Core Concept:
- Follow particular naming conventions with prefix HTTP verb like:
- OnGet or OnGetAsync
- OnPost or OnPostAsync
- OnPut or OnPutAsync
- Note We can only have one of action handler, either OnPost() or OnPostAsync() otherwise will get
- 500 Internal Server Error. InvalidOperationException: Multiple handlers matched. The following handlers matched route data and had all constraints satisfied:
- References
- Basic Other
- Basic start from Official
- Introduction from Official
- Advance XSRF/CSRF and Razor Pages
Get Method Ajax Call Demo in Asp.net Core 2.0 using JQuery
public ActionResult OnGetCountries() { //Will need to add one predefined request, handler=Countries in Url. List<string> countryNames = new List<string>(); foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { var country = new RegionInfo(new CultureInfo(cul.Name, false).LCID); countryNames.Add(country.DisplayName.ToString()); } return Content(JsonConvert.SerializeObject(countryNames.Distinct())); }
public JsonResult OnGetCountriesStartwith(string startWith) { //Will need to add one predefined request, handler=CountriesStartwith&startWith=A List<string> countryNames = new List<string>(); foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { var country = new RegionInfo(new CultureInfo(cul.Name, false).LCID); countryNames.Add(country.DisplayName.ToString()); } return new JsonResult(countryNames.Distinct().Where(o => o.StartsWith(startWith))); }
POST Method Ajax Call Demo in Asp.net Core 2.0 using JQuery
public JsonResult OnPost() { MemoryStream stream = new MemoryStream(); Request.Body.CopyTo(stream); stream.Position = 0; using (StreamReader reader = new StreamReader(stream)) { string requestBody = reader.ReadToEnd(); if (requestBody.Length > 0) { //do your technical stuff to add country. } } return new JsonResult("Country Added."); }
Client Page in which we are using JQuery in order to call above defined action.
<h1>Client Page</h1>
<a href="javascript:void(0)" onclick="getCountries()">All Countries</a> </br></br>
<input id="startwith" type="text" /> <a href="javascript:void(0)" onclick="getCountriesStartWith()">Countries StartWith</a> </br></br>
<a href="javascript:void(0)" onclick="UpdateCountries()">Update Countries</a> </br></br>
@Html.AntiForgeryToken()
<div id="result">Result will be here</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function getCountries() {
console.log('getCountries');
$('#result').html('Loading..');
$.ajax({
type: "GET",
url: "handler?handler=countries",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#result').html('All Countries name: ');
for (var i = 0; i < response.length; i++) {
$('#result').append('<div>' + response[i]+'</div>');
}
},
failure: function (response) {
alert(response);
}
});
}
function getCountriesStartWith() {
console.log('getCountriesStartWith');
var startwith = $('#startwith').val();
console.log(startwith);
$('#result').html('Loading..');
$.ajax({
type: "GET",
url: "handler?handler=countriesstartwith&startWith=" + startwith,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#result').html('Countries starting with : ' + startwith);
for (var i = 0; i < response.length; i++) {
$('#result').append('<div>' + response[i] + '</div>');
}
},
failure: function (response) {
alert(response);
}
});
}
function UpdateCountries() {
console.log('UpdateCountries');
$('#result').html('Updating..');
$.ajax({
type: "POST",
url: "handler",
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{country : "XYZ"}',
success: function (response) {
$('#result').html(response);
},
failure: function (response) {
alert(response);
}
});
}
</script>
This is how we can set header in JQuery Ajax Call.
$.ajax({ type: "POST", url: "/" , //beforeSend: function (xhr) { // xhr.setRequestHeader("XSRF-TOKEN", // $('input:hidden[name="__RequestVerificationToken"]').val()); //}, //or //headers: { // "XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val() //}, data: JSON.stringify(model), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { //.. }, failure: function (response) { alert(response.d); } });
This is how we can inject Antiforgery service in startup.cs.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAntiforgery(option => { option.HeaderName = "XSRF-TOKEN"; option.SuppressXFrameOptionsHeader = false; } ); }
To explicitly disable Antiforgery add given line of code in statup.cs.
services.AddMvc().AddRazorPagesOptions(options => { options.RootDirectory = "/Pages"; options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); });