我正在尝试使用自定义属性开发需要授权的WCF休息服务。
如果授权密钥在实现IOperationBehavior和IParameterInspector的自定义属性中无效,我想将响应作为401状态代码发送。
任何人都可以告诉我如何将401状态代码作为自定义属性的响应发送。
这是实施
public class AuthorizationAttribute : Attribute,IOperationBehavior,
IParameterInspector
{
#region IOperationBehavior Members
public void ApplyDispatchBehavior(OperationDescription operationDescription,
System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
dispatchOperation.ParameterInspectors.Add(this);
}
#endregion
#region IParameterInspector Members
public object BeforeCall(string operationName, object[] inputs)
{
string publicKey =
WebOperationContext.Current.IncomingRequest.Header["Authorization"];
if (publicKey == "592F2D7E-5E9C-400D-B0AE-1C2603C34137")
{
}
else
{
// Here i would like to send the response back to client
with the status code
}
}
return null;
}
#endregion
}
[Authorization]
public bool signin(string username, string password)
{
}
答案 0 :(得分:1)
抛出WebFormatException
throw new WebFaultException(HttpStatusCode.Unauthorized);
答案 1 :(得分:0)
如果您正在使用WCF Rest Starter工具包,您也可以这样做:
throw new Microsoft.ServiceModel.Web.WebProtocolException(System.Net.HttpStatusCode.Unauthorized, "message", ex);
如果需要,该方法会有更多重载。
答案 2 :(得分:0)
public string CreateError(int code ,string description)
{
Context.Response.StatusCode = code;
Context.Response.StatusDescription = description;
Context.ApplicationInstance.CompleteRequest();
return null;
}
然后从您的Web服务方法中使用此方法返回错误示例:
return CreateError(403, "Request denied by server");
答案 3 :(得分:0)
如果无法在WCF服务中启用aspnetcompatibilityMode
,则可以执行以下操作。
您必须拦截消息并在wcf消息的 HttpResponseMessageProperty
中设置状态代码。我使用 CustomErrorHandler
来做到这一点,并且效果很好。
public class CustomErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
fault.Properties[HttpResponseMessageProperty.Name] = new HttpResponseMessageProperty()
{
StatusCode = statusCode
};
}
}
以下代码用于将CustomErrorHandler注入到 ServiceBehavior
中。
public class CustomServiceBehaviour : IServiceBehavior
{
... other IServiceBehavior methods
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
{
channelDispatcher.ErrorHandlers.Add(new CustomErrorHandler());
}
}
}
然后在web.config中使用serviceBehavior
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="CustomServiceBehavior" type="MyNamespace.CustomServiceBehavior, MyAssembly" />
</behaviorExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior name="CustomBehavior">
<CustomServiceBehavior />
</behavior>
</serviceBehaviors>
</behaviors>
<service behaviorConfiguration="CustomBehavior" name="SomeService">
<endpoint ..../>
</service>
</system.serviceModel>