如何使用jquery客户端从另一个域POST到启用Web api的服务器

How to POST to a Web API2 Cors enabled server from another Domain with a *jquery* client

本文关键字:启用 Web api 服务器 POST jquery 何使用 客户端 另一个      更新时间:2023-09-26

我看过类似的帖子,我自己也做过类似的(但略有不同)。我试图在这里包括所有的信息,同时保持尽可能简单。

我开始玩Web API版本1,现在我正在看版本2,有内置的Cors支持,我认为很棒(因为我以前遇到过Cors的麻烦)

在Dev studio 2013中,我创建了一个stock MVC Web-Api项目,并在WebApiConfig.Register中包含以下行。

public static class WebApiConfig
{
  public static void Register(HttpConfiguration config)
  {
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));    
    ...
为了进行测试,我用下面的脚本创建了一个简单的HTML客户端。
$(document).ready(function() {
    $.support.cors = true;
    $.ajaxSetup({
      cache: false
    });
....
function postdata() {
  var data = {
        s1: 'test',
        s2: 'test2'
      };
  $.ajax({
   url: url,
   data: data,
   type: "POST",                                    
   datatype: 'application/json'})   
     ....

我在运行Web API服务的同一台机器上测试了这个脚本,它运行得很好。在服务器方法中遇到了一个断点,并调用了成功调用。

然后我想在另一台机器上测试这个,我们的网络(实际上它与运行服务器的机器连接在同一个交换机上)

我使用tping来确保我可以访问运行web-api服务的服务器上的端口(我可以)

在另一台机器上运行,我现在得到以下错误显示在Chrome控制台(我刚刚删除了我的ip和路由)

XMLHttpRequest cannot load http://<myip>:62594/<myroute>. 
No      'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access. 

在fiddler原始视图中(在客户端机器上),我看到以下请求

POST http://<serverip>:62594/<my route> HTTP/1.1
Host: <serverpp>:62594
Connection: keep-alive
Content-Length: 68
Accept: */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)     Chrome/33.0.1750.154 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
s1=test&s2=test2

和下面的响应…

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 17 Mar 2014 03:55:55 GMT
Connection: close
Content-Length: 334
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>

在服务器机器上,我在fiddler中看不到任何东西,当然,我的api方法没有被调用。

我在ajax调用的标题中添加了以下内容

 $.ajax({
        url: url,
        data: data,
        type: "POST",               
        headers: { 'Access-Control-Allow-Origin' : '*',
                   'Origin' : <my client ip>},          
        datatype: 'application/json'})  

现在Chrome控制台显示。

 Refused to set unsafe header "Origin" jquery-2.0.2.min.js:6
 OPTIONS http://<serverip>:62594/<my route> 400 (Bad Request) jquery- 2.0.2.min.js:6
 OPTIONS http://<serverip>:62594/<my route> No 'Access-Control-Allow-    Origin' header is present on the requested resource. Origin 'null' is therefore not allowed  access. jquery-2.0.2.min.js:6
XMLHttpRequest cannot load http://<my server ip>:62594/<my route>. No   'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

在客户端提琴我看到以下请求…

OPTIONS http://<my server ip>:62594/<my route> HTTP/1.1
Host: <my server ip>:62594
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)     Chrome/33.0.1750.154 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin, accept, content-type
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

和下面的回复…

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 17 Mar 2014 05:47:12 GMT
Connection: close
Content-Length: 334
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML  4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>

我不知道为什么在fiddler它报告坏的主机名,当我试图设置的起源(这是抱怨),它不会让我(所以它仍然是null)

有没有人知道如何使用jquery来进行这样的调用?如果这是可能的,如果是,我需要使用什么语法(一个确切的示例调用将是伟大的),或者有一些其他的浏览器设置需要设置?

这里的任何信息将非常感激!

提前谢谢你,Peter

就像我正在寻找一些更多的信息来添加(像我从开发工作室内运行我的服务器的事实),我发现了我的问题!

我注意到我在IIS express下运行,所以(不知道太多关于IIS express vs IIS,我将服务器更改为本地IIS,在那里它创建了一个虚拟目录http:///WebApiTestRoutes

然后我在我的路由中使用了下面的…

http://<serverip>/WebApiTestRoutes/<my route>

无端口。此外,我不需要任何标题在ajax调用,我只使用

$.ajax({
        url: url,
        data: data,
        type: "POST",                               
        datatype: 'application/json'})  

现在在远程机器上一切正常!

我在这里留下了这篇文章,以防其他人在测试时没有想到同样的事情(即iis express vs iis local),对于一个新手来说,这让我困惑了好几天!