Processing AJAX requests in ASP. NET Core Razor

Source: Internet
Author: User
Tags response code

How to process AJAX requests in ASP. Razor in ASP. Razor (hereinafter referred to as Razor) just came out, looked at the official documents, has not been used. Busy today, ready to use Rozor to do a project proficiency, the results of writing the first page is stuck. Toss half a day to do well, the following for everyone to share the next solution. Let's start by giving you a brief introduction. Razorrazor pages is a new feature of the ASP. NET core, which makes it easier and more efficient to program your pages. The Razor page uses a handler method to process incoming HTTP requests (Get/post/put/delete). These action methods are similar to the ASP. NET MVC or Web API. Razor pages follows a specific naming convention, as is the handler method. They also follow specific naming conventions and are prefixed with the "on" prefix: As with HTTP verbs onget (), Onpost () and other processing methods also have asynchronous versions: Ongetasync (), Onpostasync (), and so on. After the introduction of razor, the direct function is very simple, is a login. The user clicks the "login button" and uses jquery to get the value of the text box and asynchronously submits it to the server. Very simple function, I believe we have written many times. The code just snapped.
# #前台代码 <form method= "POST" > <div class= "login-ic" > <i></i>            <input asp-for= "Login.username" id= "UserName"/> <div class= "clear" > </div> </div> <div class= "Login-ic" > <i class= "icon" ></i> < Input id= "PassWord" asp-for= "Login.password"/> <div class= "clear" > </div> </ div> <div style= "MARGIN-TOP:-0.5EM;" > <ul> <li> <input type= "checkbox" id= "Brand1"                Value= "" > <label for= "Brand1" > Remember me </label> </li>                </ul> <a href= "#" > Forgot password? </a> </div> <div class= "log-bwn" style= "MARGIN-TOP:4EM;" > <input tyPe= "button" value= "Login" id= "Btnlogin" > </div> <div class= "log-bwn" style= "MARGIN-TOP:1EM; "> <input type=" button "value=" register "onclick=" location.href= '/user/register ' "> &LT;/DIV&G t;</form># #Script代码 $ ("#btnLogin"). Click (function () {$.post ('/user/login?hanler=loginin ', {username:$ (" #UserName "). Val (), password:$ (" #PassWord "). Val ()}, function (data) {Console.log            (data);        });    }); # #后台代码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> Onpostlogininasync () {//if (modelstate.isvalid)//{//V        AR 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 ("parameter fill error, please check!")); }}
First explain the next/user/login?hanler=loginin what this URL means, user is a directory under my page, Login is a page, Loginin is a corresponding method in the page. The URL is to give this request to the Onpostlogininasync () method to handle. As for why is loginin and not onpostlogininasync, at the beginning of the article also mentioned, this is Rozar grammar limit, not clear friends can go to look at Microsoft's official documents, write certainly better than me. This code at first glance, the idea is clear, the project ran up, take a wave to see. Yes, you read it right, Response code 400. A variety of posture test for a long time, is 400, you must now want to know, the above code what is the problem. Well, the above code is not wrong. The reason is that Razor was designed to automatically prevent cross-site request forgery (CSRF/XSRF) attacks. You don't have to write any other code. The Razor page automatically contains security token generation and validation. The request failed here because Post did not commit the AntiForgeryToken. There are two ways to add AntiForgeryToken.
    • in ASP. NET Core MVC 2.0, Formtaghelper injects an anti-forgery token into an HTML form element. For example, the following tag in the razor file will automatically generate an anti-counterfeiting tag:

      <form method="post"><!-- form markup --></form>
    • Explicitly add use @Html. AntiForgeryToken ()

To add AntiForgeryToken, we can use any method. Both of these methods add a hidden name to the input type __requestverificationtoken. The AJAX request should send the security token in the request header to the server. So, 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 modified code adds a "Xsrf-token" ID to the request header before sending the request, and the value is the auto-generated security token for the form. Since "Xsrf-token" is our own addition, the framework itself will not be recognized, so 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 service side can receive the POST request normally. It took a while to solve the problem .... After solving the Niu Jiao Jian found himself before drilling,, in fact, there are more simple methods. It's too late, test it tomorrow, make it back if it works.

Processing AJAX requests in ASP. NET Core Razor

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.