【发布时间】:2016-01-09 03:09:09
【问题描述】:
我阅读了如何在 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
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>
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>
按刷新按钮(GET)成功检索员工信息列表。但是,更新、删除和添加失败。 该图显示了在 chrome 中按下“添加”按钮后的状态 405 错误。
非常感谢您的建议和帮助!
【问题讨论】: