我阅读了《如何创建WCF Restful》教程,并从WCFTutorial下载了示例代码。
其中包括一个主机(名称:MYFirstRestfulServiceHost)和一个客户端(名称:WebClient)。
WebClient和MYFirstRestfulServiceHost位于不同的域中。
因此,当我进行GET / POST请求时,遇到了一个问题:状态码为405“方法不允许”。
经过两天的研究,我发现我必须在Host app.config中添加一些配置才能在跨域wcf服务上执行GET / POST请求。
在app.config中添加配置后,我成功在WebClient中执行了GET请求,但无法通过按下按钮在WebClient中执行剩余的POST,DELETE和PUT请求。
请指导我还需要配置什么以使其成功。
以下是源代码和配置:
非常感谢您的建议和帮助!
经过两天的研究,我发现我必须在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);
}
}
我的第一个Restful服务主机
app.config
<?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>
我的第一个RESTful服务主机
Program.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();
}
}
WebClient
Default.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>
通过点击“刷新”按钮(GET),成功检索到员工信息列表。然而,更新、删除和添加操作失败。
在Chrome中点击添加按钮后,图像显示状态405错误。
![enter image description here](https://istack.dev59.com/fyGNL.webp)