I have two project such as Main Project in Dot net Core MVC and Target project in ASP.NET framework webforms I have a Test Method in Webform in Target Project , But I want access the method from Main project using jQuery Ajax But this Code Does not hit the target Method..
From Main Project
$('#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";
}
}
}
CodePudding user response:
ASP.NET AJAX page methods only support POST requests for security reasons. If you change the method to POST
, you can't use JSONP
as dataType.
Change your code in ASP.NET Core
below:
<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>
Be sure you have configured cors in web.config
file in 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>
Be sure change your RouteConfig.cs
in App_Start
folder in 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);
}
}