gpt4 book ai didi

jquery - WCF Restful CORS 执行 POST 失败

转载 作者:行者123 更新时间:2023-12-01 01:14:11 26 4
gpt4 key购买 nike

我阅读了如何在WCF中创建Restful教程并从 WCFTutorial 下载示例代码。有 1 个主机(名称:MYFirstRestfulServiceHost)和 1 个客户端(名称:WebClient)。WebClient 和 MYFirstRestfulServiceHost 位于不同的域中。因此,当我发出 GET/POST 请求时,我遇到了一个问题:状态 405“方法不允许”。

经过 2 天的研究,我发现我必须在 Host app.config 中添加一些配置才能对跨域 wcf 服务执行 GET/POST 请求。

在 app.config 中添加配置后,我成功在 WebClient 中执行 GET 请求,但无法通过从 WebClient 按下按钮来执行其余的 POST 、 DELETE 和 PUT 。

请建议我还应该配置什么才能成功。

下面是源代码和配置:

IEmployeeService.cs

namespace MyFirstRESTfulService
{
[ServiceContract()]
public interface IEmployeeService
{
[WebGet(UriTemplate = "Employee", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
List<Employee> GetAllEmployeeDetails();

[WebGet(UriTemplate = "Employee?id={id}", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Employee GetEmployee(int Id);

[WebInvoke(Method = "POST", UriTemplate = "EmployeePOST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
[OperationContract]
void AddEmployee(Employee newEmp);

[WebInvoke(Method = "PUT", UriTemplate = "EmployeePUT", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
[OperationContract]
void UpdateEmployee(Employee newEmp);

[WebInvoke(Method = "DELETE", UriTemplate = "Employee/{empId}", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
void DeleteEmployee(string empId);
}
}

EmployeeService.cs

namespace MyFirstRESTfulService
{
[ServiceContract()]
public interface IEmployeeService
{
[WebGet(UriTemplate = "Employee", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
List<Employee> GetAllEmployeeDetails();

[WebGet(UriTemplate = "Employee?id={id}", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Employee GetEmployee(int Id);

[WebInvoke(Method = "POST", UriTemplate = "EmployeePOST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
[OperationContract]
void AddEmployee(Employee newEmp);

[WebInvoke(Method = "PUT", UriTemplate = "EmployeePUT", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
[OperationContract]
void UpdateEmployee(Employee newEmp);

[WebInvoke(Method = "DELETE", UriTemplate = "Employee/{empId}", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
void DeleteEmployee(string empId);
}
}

MyFirstRestfulServiceHost

应用程序配置

<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true"></standardEndpoint>
</webHttpEndpoint>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true"></standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
</system.serviceModel>

</configuration>

MyFirstRESTfulServiceHost

程序.cs

static void Main(string[] args)
{
try
{

Uri httpUrl = new Uri("http://localhost:8090/MyService/EmployeeService");
WebServiceHost host = new WebServiceHost(typeof(MyFirstRESTfulService.EmployeeService), httpUrl);
host.Open();

foreach (ServiceEndpoint se in host.Description.Endpoints)
Console.WriteLine("Service is host with endpoint " + se.Address);
Console.WriteLine("Host is running... Press <Enter> key to stop");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}

网络客户端

默认.aspx

 <script type="text/javascript" >
function RefreshPage() {
var serviceUrl = "http://localhost:8090/MyService/EmployeeService/Employee";
$.ajax({
type: "GET",
url: serviceUrl,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
success: function (data) {
var itemRow = "<table>";
$.each(data, function (index, item) {
itemRow += "<tr><td>" + item.EmpId + "</td><td>" + item.Fname + "</td></tr>";
});
itemRow += "</table>";

$("#divItems").html(itemRow);

},
error: ServiceFailed
});
}

function POSTMethodCall() {
var EmpUser = [{ "EmpId": "13", "Fname": "WebClientUser", "Lname": "Raju", "JoinDate": Date(1224043200000), "Age": "23", "Salary": "12000", "Designation": "Software Engineer"}];
var st = JSON.stringify(EmpUser);
$.ajax({
type: "POST",
url: "http://localhost:8090/MyService/EmployeeService/EmployeePOST",
data: JSON.stringify(EmpUser),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
// Play with response returned in JSON format
},
error:ServiceFailed
});

}
function DELETEMethodCall() {
$.ajax({
type: "DELETE",
url: "http://localhost:8090/MyService/EmployeeService/Employee/2",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
// Play with response returned in JSON format
},
error: function (msg) {
alert(msg);
}
});

}

function PUTMethodCall() {
var EmpUser = [{ "EmpId": "3", "Fname": "WebClientUser", "Lname": "Raju", "JoinDate": Date(1224043200000), "Age": "23", "Salary": "12000", "Designation": "Software Engineer"}];
$.ajax({
type: "PUT",
url: "http://localhost:8090/MyService/EmployeeService/EmployeePUT",
data: EmpUser,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
alert('success');
// Play with response returned in JSON format
},

error: ServiceFailed
});

}
function ServiceFailed(xhr) {
alert("response:" + xhr.responseText);

if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}

return;
}
</script>
<input type="button" onclick="PUTMethodCall();" name="btnUpdate" value ="Update" />
<input type="button" onclick="DELETEMethodCall();" name="btnDelete" value ="Delete" />
<input type="button" onclick="POSTMethodCall();" name="btnAdd" value ="Add" />
<input type="button" onclick="RefreshPage()" name="btnRefesh" value ="Refresh" />
<div id="divItems"></div>

enter image description here

按刷新按钮(GET)成功检索员工信息列表。但是,更新、删除和添加失败。该图显示了在 Chrome 中按“添加”按钮后出现的状态 405 错误。 enter image description here

非常感谢您的建议和帮助!

最佳答案

我不认为这里的问题是由 CORS 引起的,但事实上它实际上是一个 GET 请求,而不是所需的 POST。

$.ajax({
type: "POST",
url: "http://localhost:8090/MyService/EmployeeService/EmployeePOST",
data: JSON.stringify(EmpUser),
contentType: "application/json; charset=utf-8",

dataType: "jsonp",
^^^^^^^^^

success: function (data) {
// Play with response returned in JSON format
},
error:ServiceFailed
});

JSONP 是一种避免发出跨源 ajax 请求的机制,并且 JSONP 请求将始终使用 GET 发送。

您应该将数据类型设置为您期望 API 提供的数据类型。

当发出跨源ajax请求时,浏览器将首先发出OPTIONS请求。这称为预检,您可以在此处阅读更多相关信息: MDN - CORS - Preflighted requests

要启用此功能,您需要在 IEmployeeService.cs 中为 OPTIONS 方法创建一条路由,并返回一个带有 200 的空响应。您的配置文件似乎设置了正确的 header 。

关于jquery - WCF Restful CORS 执行 POST 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com