我正在从我的WCF REST服务执行GET,POST和DELETE操作。虽然GET& POST工作正常,DELETE无效。
从我的客户端应用程序,当我尝试调用delete时,它说下面的错误。 错误消息:远程服务器返回错误:(403)禁止。
我的代码:
数据合同:
[WebInvoke(Method = "DELETE", UriTemplate = "users/", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
string DeleteUser(UserInfo userinfo);
实施
public string DeleteUser(UserInfo userinfo)
{
string sResult = "";
try
{
UserDataAccess dataAccess = new UserDataAccess();
sResult = dataAccess.DeleteUser(userinfo.GEId);
}
catch (Exception ex)
{
oLog.LogError(ex, true);
sResult = ex.Message;
}
return sResult;
}
消费代码:
protected void btDeleteAsJson_Click(object sender, EventArgs e)
{
UserInfo user = new UserInfo();
user.GEId = Convert.ToInt32(txtGEID.Text);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string output = jsSerializer.Serialize(user);
SendMessageDeleteJson(apiUrl, output);
}
public void SendMessageDeleteJson(string endPoint, string output)
{
string data = output;
byte[] bytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = CreateWebRequest1(endPoint, bytes.Length, "application/json");
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("DELETE failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string sResponseStream = reader.ReadToEnd();
lblDeleteSuccess.Text = "Success! User has beed deleted";
}
}
private HttpWebRequest CreateWebRequest1(string endPoint, Int32 contentLength, string ContentType)
{
var request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = "DELETE";
request.ContentLength = contentLength;
//request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = ContentType;
return request;
}
你能指点我错在哪里吗?
答案 0 :(得分:1)
我会尝试将SetEntitySetAccessRule添加到AllRead,AllWrite或其他选项中:
public class WcfDataService1 : DataService< HenryContext >
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
答案 1 :(得分:0)
我最近遇到了同样的问题,这是由于WebDAV拦截了请求。删除该应用程序的模块解决了这个问题。
在IIS 7上:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
在IIS 6上:
<system.web>
<httpModules>
<remove name="WebDAVModule" />
<!-- ... -->
</httpModules>
</system.web>