跨域发布到 ASP.Net MVC 应用程序

问题描述:

我正在开发一个应用程序,其中 HTML 和 javascript 块被传送到不同的客户端.我可以通过将以下内容添加到 web 配置文件来获取 html/javascript 块:

I'm developing an app where HTML and javascript chunks are delivered down to different clients. I'm able to GET the html/javascript chunks by adding the following to web config file:

  <system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
  <httpProtocol>
      <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
      </customHeaders>
  </httpProtocol>

这对于执行 GETS 非常有用.我遇到的问题是使用 jQuery 进行跨域 POST:

This is working great for doing GETS. The problem I'm running into is doing POSTs cross domain using jQuery:

        $.ajax(
    {
        type: 'POST',
        url: url,
        crossDomain: true,
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json',
        success: function(responseData, textStatus, jqXHR) 
        {
            alert('Success');
        },
        error: function (responseData, textStatus, errorThrown) 
        {
            alert('POST failed.');
        }
    });

我会有很多客户使用我的应用程序(希望如此).我考虑过使用代理,但我无法控制客户端服务器,所以我无法安装 httpHandler 来充当代理.

I will have numerous clients consuming my app (hopefully). I thought about using a proxy, but I do not have control of the client servers so I'm not able to install a httpHandler to act as a proxy.

关于如何将来自不同客户端的 json 数据跨域发布到我的 ASP.Net MVC 应用程序的任何建议?

Any suggestions on how I can POST json data from different clients cross domain to my ASP.Net MVC app?

我摆弄了我的 ajax 调用,它似乎有效(与上面的 ajax 调用相比):

I fiddled with my ajax call and it seems to be working (compare to the ajax call above):

        $.ajax(
    {
        type: 'POST',
        url: url,
        crossDomain: true,
        data: data,
        dataType: 'json',
        success: function(responseData, textStatus, jqXHR) 
        {
            alert('success');
        },
        error: function (responseData, textStatus, errorThrown) 
        {
            alert('POST failed.');
        }
    });

我删除了contentType: 'application/json'"和JSON.stringify(...)"调用,我可以发布到服务器.

I removed "contentType: 'application/json'" and "JSON.stringify(...)" calls and I'm able to post to the server.

我不知道如何解释它的工作原理.有任何想法吗?是否存在任何安全问题?我在我的笔记本电脑上做这一切.我通过 IIS 7 设置了 2 个不同的网站.这会有所不同吗?

I'm not sure how to explain why it's working. Any ideas? Are there any security issues? I'm doing this all on my laptop. I set up 2 different websites via IIS 7. Will this make a difference?