【问题标题】:Ajax always go on 'Error' (C# MVC 5) on Cross-Domain requestAjax 在跨域请求时总是出现“错误”(C# MVC 5)
【发布时间】:2017-02-22 23:34:13
【问题描述】:

我有这个 C# 方法:

C#

[HttpPost]
[AllowAnonymous]
public JsonResult PostOnCRM(string textBoxFirstName, string textBoxCountry, string textBoxLastName, string textBoxEmail, string textBoxTitle, string textBoxTelephone, string textBoxCompany, string textBoxWebsite, string textAreaNote, string checkBoxUpdates)
{

        bool isValidEmail = Regex.IsMatch(textBoxEmail,
        @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
        @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
        RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));

        if (!isValidEmail)
            throw new Exception("E-mail is not a valid one");
        LeadInformation lead = new LeadInformation()
        {
            Subject = "Web site",
            FirstName = textBoxFirstName,
            LastName = textBoxLastName,
            JobTitle = textBoxTitle,
            Address1_Country = textBoxCountry,
            EmailAddress1 = textBoxEmail,
            MobilePhone = textBoxTelephone,
            WebsiteUrl = textBoxWebsite,
            Description = textAreaNote,
            DoNotEmail = checkBoxUpdates.Contains("Yes") ? true : false
        };


        //Some method that works well go here

        return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}

在我看来,这个 Ajax 调用

Ajax

$("#formContact").submit(function (evt) {
evt.preventDefault();

var formdata = $('form').serialize();
$.ajax({
    type: 'POST',
    dataType: "json",
    cache: false,
    url: 'http://localhost:59289/Lead/PostOnCRM',
    data: formdata,
    success: function (response) {
        alert('success!');
    },
    error: function (response) {
        alert('Error! try again later');
    }
});
});

该方法执行完美。是否在数据库中插入,但是当它返回到 ajax 方法时,它总是落在“错误”上,并且不返回我发送的响应。会是什么?

很抱歉以这种方式获取参数(尤其是 bool 值的东西)并且不使用 Bind 或任何东西,但这与问题无关

我在葡萄牙语 StackOverflow 上问过这个问题,但没有得到很好的答案。

在这里,我的浏览器打印 https://postimg.cc/image/e86q3hcol/

【问题讨论】:

  • 错误响应中返回的错误详情是什么?
  • 用调试器运行你的控制器;逐步验证它是否成功返回。接下来,使用浏览器的调试监视器观察网络请求,并验证成功的响应状态代码、标头、消息。显示您收到的错误error: function(jqxhr, status, error) { console.log(jqxhr, status, error); }
  • 臭,这只是一个“中止”。 “错误”响应中没有任何内容。
  • Jansen,始终是 200 码状态。错误:"" 状态:"错误
  • 我正在接收一个对象。我唯一能说的是它在中止时具有和长度为 1:|我没有找到任何有帮助的东西。我应该寻找什么?我在邮递员那里发布了正确的 json 响应,但在 ajax 却返回错误:/

标签: c# jquery ajax asp.net-mvc cross-domain


【解决方案1】:

首先,您不应该使用正则表达式来验证电子邮件地址。看this

其次,你想在 ASP.Net MVC 中使用 Model,而不是在 action 方法中声明多个参数。

请做它的财产。如果您仍有疑问,请回来再次询问。这是一个工作示例 -

查看

@model UserModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.TextBoxFor(model => model.Email)
        <button id="btnSubmit" type="button">Submit</button>
    }
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <script>
        $(function () {
            $("#btnSubmit").click(function () {
                var data = {
                    Email: $("#Email").val()
                };
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    url: "@Url.Action("PostOnCRM", "Lead")",
                    data: JSON.stringify(data),
                    success: function (response) {
                        alert('success!');
                    },
                    error: function (response) {
                        alert('Error! try again later');
                    }
                });
            });
        });
    </script>

</body>
</html>

查看

public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Country { get; set; }
    public string Email { get; set; }
}

控制器

public class LeadController : Controller
{
    public ActionResult Index()
    {    
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public JsonResult PostOnCRM(UserModel model)
    {
        bool isValidEmail = IsValidEmail(model.Email);

        if (!isValidEmail)
            throw new Exception("E-mail is not a valid one");

        // ...

        return Json(new { success = true, responseText = "Your message successfuly sent!" });
    }

    public static bool IsValidEmail(string email)
    {
        if (String.IsNullOrWhiteSpace(email))
            return false;

        try
        {
            email = new MailAddress(email).Address;
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }
}

【讨论】:

  • 我无法说出问题的原因,因为代码没有遵循 ASP.Net MVC 中的最佳实践。
  • 是的,我知道。这是一个漫长的悲伤故事:(
【解决方案2】:

我的老板在 5 分钟内解决了我的问题(我尝试了 2 天)

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

在 web.config 上:|

我不知道为什么。谁能给我解释一下?

我忘了说,但这是一个跨源请求:|

【讨论】:

  • 事情太多很容易出错。如果您在原始问题中提到 CORS,我们可以立即指出它。 &lt;add name="Access-Control-Allow-Origin" value="*" /&gt; 可能会带来安全风险,具体取决于您的要求。
猜你喜欢
  • 2013-01-28
  • 2021-11-26
  • 1970-01-01
  • 2015-06-08
  • 2018-04-12
  • 2013-08-09
  • 1970-01-01
  • 2015-05-05
  • 2014-07-18
相关资源
最近更新 更多