"ASP. net Core" resolves "the required antiforgery cookie" XXX "is not present" error

Source: Internet
Author: User

When you post content with form on a page, you may encounter the following exception:

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

Let's try to reproduce the mistake. Create a new ASP. NET Core Project, template choose "Empty" on the line, this is the old week favorite project template, empty = = free.

Create a directory under the project, called pages, to place Razor pages, and then build a index.cshtml page.

The reason is called index.cshtml because Index is the name of the default page, so the input root URL can be accessed. If you don't call Index, like this.

At this point you can add a demo to the root URL and you can configure page routing in the Startup.configureservices method if you want to access it in the root directory.

         Public void configureservices (iservicecollection services)        {            = =            {                o.conventions.addpageroute ("/demo  """);            });        }

Be sure to note the case when you write the path, and do not need to pay attention when typing in the browser, but be careful when programming. The Addpageroute method is an extension method, the pagename parameter indicates the target page you want, such as I want to reach/demo page, route parameter set the route, empty string represents the root path. If I enter http://somehost/in the browser, I can navigate to the Http://somehost/Demo page.

If PAGENAME is the/users/newone,route parameter for new, then your access to Http://somehost/new will point to Http://somehost/users/newone.

You should be aware that this Razor page routing rule is only for Web Pages, not MVC's routing rules, this setting does not work for MVC, MVC can use a similar {controller]/{action}/{id} route, which I believe you are very skilled (when If you have written the MVC application).

By the way, add the use code to the Configure method, either 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, you find that the corresponding Pagemodel class, where the old week recommended to use _viewimports file to deal with.

Add a view import file under the Pages directory.

Then, introduce the namespaces that you want to use.

@using websample09@using Websample09.pages

But this is not perfect, but also add a line.

@namespace websample09.pages

The @namespace directive is used to set the namespace of the code generated by the Razor page, which ensures that the page is in the same namespace as the Pagemodel type and avoids any future errors.

Save and close the Import page and go back to the page you just added.

@page @model Demomodel<!DOCTYPE HTML><HTML><Head>    <MetaCharSet= "Utf-8" />    <Metaname= "Viewport"content= "Width=device-width, initial-scale=1.0, User-scalable=no" />    <title>Example</title></Head><Body>    <formMethod= "POST">        <label for= "Parm">Please feel free to enter:</label>        <inputtype= "text"name= "Parm" />        <Buttontype= "Submit">Submit</Button>    </form></Body></HTML>

Open the corresponding Pagemodel class code and write a Onpost method.

 Public void Onpost (string  parm)        {            viewdata["data"] = $"  The value you entered is: {parm}";        }

After POST, through the Parm parameter (the same name as the field in the page form element, will automatically assign values) to get the input, save to ViewData, in order to display on the page, we go back to the page, plus a P element, to display the input content.

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

OK, now it's time to test.

Run and go to the page.

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

The Console log now records the next exception.

That's the mistake we started with, this verification is primarily for security reasons, to prevent someone from stealing your data and then spoofing the server across domains.

So, how to solve it? You may not believe it, it's simple.

Just open the view that we added to the project, import the page, and add a Tag Helper for the form element.

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

The format is this, very general, is the. NET type representation, separated by a comma in English, preceded by the type (including the namespace), followed by the assembly name.

The Code Editor is displayed in this color before the tag helper is added.

When the marker helper is added, it is displayed as this color.

It's time to go.

Let's look at the difference between the HTML used to print to the client before and after applying the tag Helper.

Before the tag helper is used, there is a 400 error on commit, resulting in the following HTML:

<formMethod= "POST">        <label for= "Parm">Please feel free to enter:</label>        <inputname= "Parm"type= "text">        <Buttontype= "Submit">Submit</Button></form>

The basic is the original output.

After applying the Form element helper, the resulting HTML is as follows:

<formMethod= "POST">        <label for= "Parm">Please feel free to enter:</label>        <inputname= "Parm"type= "text">        <Buttontype= "Submit">Submit</Button>     <input  name= "__requestverificationtoken"  type= "hidden"  value= " Cfdj8deagdeorwjfuzyofcgejpswrkhd5qrw4jdarvrf3swas-tchnuqhesfwxtxtk7idcmprab241ucr6kdza-srbhnsyoe01ymgls-donlzymb-mzvmxgjm Kcn2zrymn-br8fj25nx_zvuwzhynq42das "/   >
</form>

A hidden element called __requestverificationtoken, which identifies the current request session, prevents the person from being used.

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

@addTagHelper  *, Microsoft.AspNetCore.Mvc.TagHelpers

Well, today's content is here, 88.

"ASP. net Core" resolves "the required antiforgery cookie" XXX "is not present" error

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.