我有兩個專案,例如 Dot net Core MVC 中的 Main Project 和 ASP.NET 框架 webforms 中的 Target 專案 我在 Target Project 中的 Webform 中有一個測驗方法,但我想使用 jQuery Ajax 從 Main 專案中訪問該方法但是這段代碼沒有擊中目標方法..
從主專案
$('#btnTest').click(function () {
AjaxCall();
});
function AjaxCall() {
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
url: 'https://localhost:44332/WebForm1.aspx/TestMethod',
success: function (jsondata) {
alert('Success');
},
error: function (request, error) {
alert("Failed");
}
})
}
</script>
//Target Project Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace TargetProject
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestMethod()
{
return "Success";
}
}
}





uj5u.com熱心網友回復:
出于安全原因,ASP.NET AJAX 頁面方法僅支持 POST 請求。如果將方法更改為POST,則不能JSONP用作 dataType。
在下面更改您的代碼ASP.NET Core:
<script>
$('#btnTest').click(function () {
AjaxCall();
});
function AjaxCall() {
$.ajax({
type: 'POST', //change here.....
crossDomain: true,
dataType: 'json', //change here.....
contentType: "application/json; charset=utf-8", //add this...
url: 'https://localhost:44332/WebForm1.aspx/TestMethod',
success: function (jsondata) {
alert('Success');
},
error: function (request, error) {
alert("Failed");
}
})
}
</script>
web.config確保您已在以下檔案中配置 cors WebForms:
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="accept, content-type" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
//.....
</configuration>
確保更改您的RouteConfig.csinApp_Start檔案夾WebForms:
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
settings.AutoRedirectMode = RedirectMode.Off;
routes.EnableFriendlyUrls(settings);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459887.html
