[ASP. NET Core] solves The "The required antiforgery cookie & quot; xxx & quot; is not present" error,

Source: Internet
Author: User

[ASP. NET Core] solves The "The required antiforgery cookie" xxx "is not present" error,

When you use form post content on the page, you may encounter the following exceptions:

The required antiforgery cookie "????????" is not present.

Let's reproduce the error. Create an ASP. NET Core project, and select [null] as the template. This is the favorite project template of old Zhou. Blank = free.

Create a directory named Pages under the project to put the Razor page, and then create an Index. cshtml page.

Index. cshtml is called because Index is the name of the response page and can be accessed by entering the root URL. If it is not called Index, for example.

In this case, you can add a demo to the root URL. If you want to access it in the root directory, you can also configure the page routing in the Startup. ConfigureServices method.

        public void ConfigureServices(IServiceCollection services)        {            services.AddMvc().AddRazorPagesOptions(o =>            {                o.Conventions.AddPageRoute("/Demo", "");            });        }

Note the case sensitivity when writing a path, but do not enter it in the browser. The AddPageRoute method is an extension method. The pagename parameter indicates the target page you want. For example, if you want to arrive at the/Demo page, the route parameter sets the route, and the Null String indicates the root path. That is, I enter http: // somehost/in the browser to locate the http: // somehost/Demo page.

If the pagename is/users/newone and the route parameter is new, then when you access http: // somehost/new, it will point to http: // somehost/users/newone.

Note that the razor page routing rule is only used for Web Pages, not for MVC routing rules. This setting does not work for MVC, MVC can use a route similar to {controller]/{action}/{id}. I believe you are very skilled (of course, the premise is that you have written the MVC application ).

 

By the way, add the use code in the Configure method, whether it is Web Pages or MVC.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }        app.UseMvc();        }

 

Now you can get the page. Open the page and you will find that the corresponding PageModel class is not found. Here, we recommend using the _ ViewImports file for processing.

Add a view import file under the Pages directory.

Then, introduce the namespace to be used.

@using WebSample09@using WebSample09.Pages

However, this is not perfect. We need to add a line.

@namespace WebSample09.Pages

The @ namespace command is used to set the namespace of the code generated by the Razor page. This ensures that the page and the PageModel type are in the same namespace and avoid future errors.

 

Save and close the import page and return to the newly added page.

@ Page @ model DemoModel <! Doctype html> 

Open the corresponding PageModel class code and write an OnPost method.

Public void OnPost (string parm) {ViewData ["data"] = $ "your input value is: {parm }";}

After POST, get the input content through the parm parameter (which is the same as the field name in the form element on the page and will be automatically assigned a value) and store it in ViewData. to display the content on the page, go back to the page and add a p element to display the input content.

  <p>@ViewData["data"]?.ToString()</p>

Okay. Now we can test it.

 

Run to enter the page.

 

Enter the content, click the button to submit, and you will receive the 400 error.

 

 

In this case, the Console Log records the next exception.

That is, the error we mentioned at the beginning. This verification is mainly for security consideration, to prevent others from stealing your data and then cross-origin spoofing server.

 

So what should we do? You may not believe it. It's very easy.

Open the view import page we just added to the project, and then add the Tag Helper of a form element.

@addTagHelper  Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers

The format is as follows. Normally, it is a representation of the. net type, separated by commas (,). The preceding format is type (including namespace), followed by Assembly name.

This color is displayed in the code editor before you add a Help Tag.

After the help tool is added, the color is displayed.

 

This is the case.

 

Let's take a look at the differences between the HTML output to the client before and after the app tag Helper.

Before the Help Tag is used, the error 400 is displayed during submission. The generated HTML is as follows:

<Form method = "post"> <label for = "parm"> enter: </label> <input name = "parm" type = "text"> <button type = "submit"> submit </button> </form>

It is basically the original output.

 

After the form Element helper is applied, the generated HTML is as follows:

<Form method = "post"> <label for = "parm"> enter: </label> <input name = "parm" type = "text"> <button type = "submit"> submit </button><Input name = "_ RequestVerificationToken" type = "hidden" value = "CfDJ8DEAGDEorWJFuzYOfcGEJpSWrKHd5Qrw4jdARVRF3SwAS-TChnUQHEsFWxtXTk7IDCmpRAB241ucR6kdZA-sRBHnsyOe01ymGLs-DONlZYmB-MzvmXgJmKcn2ZrYMN-Br8fj25nX_zvuwzhyNQ42Das "/>
</Form>

A hidden element named _ RequestVerificationToken is added to identify the current request session to prevent unauthorized use.

 

By the way, if you want to import various Tag Helper, you can change the type name to * (asterisk, wildcard ).

@addTagHelper  *, Microsoft.AspNetCore.Mvc.TagHelpers

 

Well, today's content is here, 88.

 

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.