如何发送状态代码作为对 WCF Rest 服务的未经授权请求的响应

发布于 2024-11-16 02:14:34 字数 1062 浏览 3 评论 0原文

我正在尝试开发一个需要使用自定义属性进行授权的 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)
{
}

I am trying to develop a WCF rest servie which needs authorization using custom attribute.

I want to send the response as 401 status code if the authorization key is not valid in custom attribute which implements IOperationBehavior and IParameterInspector.

can any one tell me how to send the 401 status code as response from the custom attribute.

Here is the implementation

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)
{
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

吃颗糖壮壮胆 2024-11-23 02:14:35

如果您的 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>

If aspnetcompatibilityMode cannot be enabled in your WCF services, then you can do as below.

You have to intercept the message and set the status code in HttpResponseMessageProperty in the wcf message. I use a CustomErrorHandler for doing that and it works fine.


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 
              };
        }
    }

Below code is for injecting CustomErrorHandler into the 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());
        }
    }
}

Then in web.config use the 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>
心碎无痕… 2024-11-23 02:14:34

抛出 WebFormatException

throw new WebFaultException(HttpStatusCode.Unauthorized);

Throw a WebFormatException

throw new WebFaultException(HttpStatusCode.Unauthorized);
丿*梦醉红颜 2024-11-23 02:14:34

如果您使用的是 WCF Rest Starter 套件,您还可以执行以下操作:

throw new Microsoft.ServiceModel.Web.WebProtocolException(System.Net.HttpStatusCode.Unauthorized, "message", ex);

如果需要,该方法还有更多重载。

If you're using WCF Rest Starter kit you can also do:

throw new Microsoft.ServiceModel.Web.WebProtocolException(System.Net.HttpStatusCode.Unauthorized, "message", ex);

That method has some more overloads if you need.

回忆那么伤 2024-11-23 02:14:34
public string CreateError(int code ,string description)
        {
            Context.Response.StatusCode = code;
            Context.Response.StatusDescription = description;
            Context.ApplicationInstance.CompleteRequest();
            return null;
        }

然后从您的网络服务方法中只需使用它来返回错误示例:

return CreateError(403, "Request denied by server");
public string CreateError(int code ,string description)
        {
            Context.Response.StatusCode = code;
            Context.Response.StatusDescription = description;
            Context.ApplicationInstance.CompleteRequest();
            return null;
        }

Then from your web service methods just use this to return errors example:

return CreateError(403, "Request denied by server");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文