How to process Ajax requests in ASP. NET Core Razor, razorajax

Source: Internet
Author: User

How to process Ajax requests in ASP. NET Core Razor, razorajax

When ASP. NET Core Razor (Razor) was just launched, I read the official documents and never used it.

Today, I have nothing to worry about. I am ready to use Rozor as a project, so I am stuck when I write the first page .. I have worked hard for half a day. I will share with you the solution below. First, we will briefly introduce Razor Pages, a new function of ASP. NET Core, which makes the programming solution of editing Pages simpler and more efficient. The Razor page uses the handler method to process incoming HTTP requests (GET/POST/PUT/Delete ). These Action methods are similar to ASP. net mvc or web api. Razor Pages follows specific naming conventions, as does the Handler method. They also follow specific naming conventions and have the same OnGet (), OnPost (), and other processing methods as the "On" Prefix: As with HTTP verbs, there are also asynchronous versions: OnGetAsync (), onPostAsync. After introducing Razor

The function is simple, that is, a logon. After you click "Log on", use Jquery to obtain the value of the text box and submit it to the server asynchronously. It is a very simple function. I believe everyone has written it many times. Just a few clicks on the code.

# Foreground Code <form method = "post"> <div class = "login-ic"> <I> </I> <input asp-for = "Login. userName "/> <div class =" clear "> </div> <div class =" login-ic "> <I class =" icon "> </ i> <input asp-for = "Login. passWord "/> <div class =" clear "> </div> <ul> <li> <input type =" checkbox "value = ""> <label for = "brand1"> remember me </label> </li> </ul> <a href = "#" rel = "external nofollow"> forgot password? </A> </div> <div class = "log-bwn"> <input type = "button" value = "Logon"> </div> <div class =" log-bwn "> <input type =" button "value =" register "> </div> </form> # Script code $ (" # btnLogin "). click (function () {$. post ('/user/Login? Hanler = LoginIn ', {UserName: $ ("# UserName "). val (), PassWord: $ ("# PassWord "). val ()}, function (data) {console. log (data) ;}) ;}## background code public class LoginModel: PageModel {private UserServiciCasee _ userService; public LoginModel (UserServiciCasee userService) {_ userService = userService ;} public void OnGet () {} [BindProperty] public UserLoginDto Login {get; set;} public async Task <ActionResult> O NPostLoginInAsync () {// if (ModelState. IsValid) // {// var user = await _ userService. LoginAsync (Login); // if (user! = Null) // {// return new JsonResult (ApiResult. ToSucess ("Login successful! "); //} // Return new JsonResult (ApiResult. ToFail (" incorrect account password! "); //} Return new JsonResult (ApiResult. ToFail (" the parameter is incorrect. Please check it! "));}}

First explain/user/Login? What does the Url hanler = LoginIn mean? user is a directory under my Page, Login is a Page, and LoginIn is a method corresponding to the Page. The request is sent to the OnPostLoginInAsync () method for processing. As to why it is LoginIn rather than onpostloginasync, I mentioned at the beginning of this article that this is the syntax limitation of Rozar. If you are not clear about it, you can go to Microsoft's official documentation and write it better than me .. At first glance, this code has a clear idea. When the project runs, let's take a look.

 

Yes, you are not mistaken. The response code is 400. After trying for half a day in various poses, It is 400. Now you must know what problems the above Code has. The above code is correct. The reason is that Razor is designed to automatically prevent cross-site Request Forgery (CSRF/XSRF) attacks. You do not have to write any other code. The Razor page automatically contains the anti-counterfeit Token Generation and verification. The request failed because the POST does not submit the AntiForgeryToken. There are two ways to add AntiForgeryToken.

In ASP. NET Core MVC 2.0, FormTagHelper injects anti-counterfeit tokens into HTML form elements. For example, the following mark in the Razor file will automatically generate the anti-counterfeit mark:

<form method="post"><!-- form markup --></form>

 

Explicitly add @ Html. AntiForgeryToken ()

To add an AntiForgeryToken, we can use any method. Both methods add a hidden name input type _ RequestVerificationToken. Ajax requests should send the anti-counterfeit mark in the request header to the server. Therefore, the modified Ajax request looks like this:

$("#btnLogin").click(function () {      $.ajax({        type: "POST",        url: "/user/Login?handler=LoginIn",        beforeSend: function (xhr) {          xhr.setRequestHeader("XSRF-TOKEN",            $('input:hidden[name="__RequestVerificationToken"]').val());        },        data: { UserName: $("#UserName").val(), PassWord: $("#PassWord").val() },        success: function (response) {          console.log(response);        },        failure: function (response) {          alert(response);        }      });    });

The improved Code adds the "XSRF-TOKEN" identifier in the Request Header prior to sending the request, with the value being the form's automatically generated anti-counterfeit flag. Since "XSRF-TOKEN" is added by ourselves and the framework itself does not recognize it, we need to add this tag to the framework:

public void ConfigureServices(IServiceCollection services){  services.AddMvc();  services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");}

Now the server can normally receive the Post request. After a long time, I finally solved the problem .... After solving the problem, I found that I had drilled the tip of the horn. In fact, there are still simpler methods .. It's too late. Test it tomorrow. If it works, make up it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.