Solution of ASP. net WebAPI cross domain call problem

  • 2021-10-16 01:26:01
  • OfStack

Find a problem

Recently, I am doing a project, the front end is VUE, the back end is WebAPI, and the business is the addition, deletion and modification of some entities. At the beginning of the project, I expected that there would be cross-domain problems, so I also found 1 data and added configuration information in Web. Config:


<httpProtocol>
  <customHeaders>
  <add name="Access-Control-Allow-Origin" value="*" />
  <add name="Access-Control-Allow-Headers" value="*" />
  <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
  </customHeaders>
 </httpProtocol>

This is one of the methods found on the Internet, and it also has its own cross-domain feature class. It can also refer to Microsoft Library cors, and a lot of information can be found on the Internet, so it will not be launched here.

After this configuration, I did Get test myself, and it was ok to call it with JQ. I thought that the cross-domain setting had been finished. However, when the sinkhole came, the Post operation could not be called, and 405 errors were returned all day, so I was depressed. What happened?

Solution

After checking the principle of cross-domain call on the Internet, it is found that there is one OPTION method call before cross-domain POST, which is used to confirm whether to run the handshake confirmation process of cross-domain POST. Then continue to look down, and find that the self-built WebAPI project through VS has OPTION processing by default, and cross-domain is not allowed by default.

So I commented out these codes in Web. Config


<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
 </handlers>

Finally, the cross-domain POST request passed, tested with JQ and axios.

Maybe, this method is not a good one, but it does solve the problem on my project, so write it down. If there is a better method, please give directions to o (*  ̄ *) o

Summarize


Related articles: