簡體   English   中英

Ajax總是在跨域請求上繼續“錯誤”(C#MVC 5)

[英]Ajax always go on 'Error' (C# MVC 5) on Cross-Domain request

我有這個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調用

阿賈克斯

$("#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/

首先, 您不應該使用正則表達式來驗證電子郵件地址。 看看這個

其次,您希望在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;
        }
    }
}

我的老板在5分鍾內解決了我的問題(我嘗試了2天)

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

在web.config上:|

我不知道為什么。 有人可以解釋一下嗎?

我忘了說,但這是一個交叉來源請求:|

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM