1

我正在使用 IE 10、Firefox 24、Chrome 29。

我有一个在 ASP.NET MVC 4 (IIS 8) 上运行的服务器,控制器中有一个简单的功能:

[HttpPost]
public ActionResult Register(string PhoneNumber, string DisplayName)
{
    // Some commented code here ...
    ViewBag.Message = "Working!";
    return View();
}

视图如下所示:

@{
    ViewBag.Title = "Register";
}
@ViewBag.Message

Ajax 调用如下所示:

$.ajax({
    type: "POST",
    url: "http://localhost:1283/home/Register",
    data: {
        phoneNumber: "123",
        displayname: "Miko"
    },
    success: function (response) {
        alert("In success: " + response);
    },
    error: function (result) {
        alert('In error: '+ result);
    }
})

在所有浏览器中,都会进行 AJAX 调用,服务器中的 Register() 会被触发,但完成后,此代码在 Internet Explorer 中运行良好,但使用 Firefox\Chrome 时总是会出现“error()”。

如何使这些功能也适用于 Firefox 和 Chrome?

谢谢。

4

1 回答 1

0

First, I think you have to take a look at Access_control_CORS.

There is a easy way to solve this problem in MVC.NET. Add Below code to Global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (!string.IsNullOrWhiteSpace(Request.Headers["Origin"]))
        {
            if (IsOriginInCrossDomainWhiteList(Request.Headers["Origin"]))
            {
                Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["Origin"]);
            }
            else
            {
                Response.End();
            }
        }
    }

    internal static bool IsOriginInCrossDomainWhiteList(string origin)
    {
        Uri uri;
        if (Uri.TryCreate(origin, UriKind.Absolute, out uri))
        {
            foreach (var whiteDomain in Properties.Settings.Default.CrossDomainWhiteList)
            {
                if (string.Compare(uri.Host, whiteDomain, true) == 0)
                {
                    return true;
                }
            }
        }
        return false;
    }

and add some domain to Web.config like :

  <applicationSettings>
     <YourProject.Properties.Settings>
      <setting name="CrossDomainWhiteList" serializeAs="Xml">
        <value>
          <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <string>www.youhost.com</string>
          </ArrayOfString>
        </value>
      </setting>
     </YourProject.Properties.Settings>
  </applicationSettings>

Then you can use ajax call at the domain added in CrossDomainWhiteList.

于 2013-09-23T02:53:42.983 回答