Freigeben über


Gewusst wie: Abfangen von Datendienstnachrichten (WCF Data Services)

Mit WCF Data Services können Sie Anforderungsnachrichten abfangen, damit Sie einem Vorgang benutzerdefinierte Logik hinzufügen können. Zum Abfangen einer Nachricht verwenden Sie besonders attributierte Methoden im Datendienst. Weitere Informationen finden Sie unter Interceptoren (WCF Data Services).

In dem Beispiel in diesem Thema wird der Northwind-Beispieldatendienst verwendet. Dieser Dienst wird erstellt, wenn Sie den WCF Data Services-Schnellstart ausführen.

So definieren Sie einen Abfrage-Interceptor für die "Orders"-Entitätenmenge

  1. Öffnen Sie im Northwind-Datendienstprojekt die Datei Northwind.svc.

  2. Fügen Sie der Codepage für die Northwind-Klasse die folgende using-Anweisung hinzu (Imports in Visual Basic).

    Imports System.Linq.Expressions
    
    using System.Linq.Expressions;
    
  3. Definieren Sie in der Northwind-Klasse eine Dienstvorgangsmethode mit dem Namen OnQueryOrders wie folgt:

    ' Define a query interceptor for the Orders entity set.
    <QueryInterceptor("Orders")> _
    Public Function OnQueryOrders() As Expression(Of Func(Of Order, Boolean))
    
    // Define a query interceptor for the Orders entity set.
    [QueryInterceptor("Orders")]
    public Expression<Func<Order, bool>> OnQueryOrders()
    

So definieren Sie einen Change-Interceptor für die "Products"-Entitätenmenge

  1. Öffnen Sie im Northwind-Datendienstprojekt die Datei Northwind.svc.

  2. Definieren Sie in der Northwind-Klasse eine Dienstvorgangsmethode mit dem Namen OnChangeProducts wie folgt:

    ' Define a change interceptor for the Products entity set.
    <ChangeInterceptor("Products")> _
    Public Sub OnChangeProducts(ByVal product As Product, _
                                ByVal operations As UpdateOperations)
    
    // Define a change interceptor for the Products entity set.
    [ChangeInterceptor("Products")]
    public void OnChangeProducts(Product product, UpdateOperations operations)
    

Beispiel

In diesem Beispiel wird eine Abfrage-Interceptor-Methode für die Orders-Entitätenmenge definiert, die einen Lambda-Ausdruck zurückgibt. Dieser Ausdruck enthält einen Delegaten, der die angeforderten Orders auf Grundlage verknüpfter Customers filtert, die einen bestimmten Kontaktnamen haben. Der Name wird wiederum auf Grundlage des anfordernden Benutzers bestimmt. In diesem Beispiel wird davon ausgegangen, dass der Datendienst innerhalb einer ASP.NET-Webanwendung gehostet wird, die WCF verwendet, und dass die Authentifizierung aktiviert ist. Die HttpContext-Klasse wird verwendet, um das Prinzip der aktuellen Anforderung abzurufen.

' Define a query interceptor for the Orders entity set.
<QueryInterceptor("Orders")> _
Public Function OnQueryOrders() As Expression(Of Func(Of Order, Boolean))
    ' Filter the returned orders to only orders 
    ' that belong to a customer that is the current user.
    Return Function(o) o.Customer.ContactName = _
        HttpContext.Current.User.Identity.Name
End Function
// Define a query interceptor for the Orders entity set.
[QueryInterceptor("Orders")]
public Expression<Func<Order, bool>> OnQueryOrders()
{
    // Filter the returned orders to only orders 
    // that belong to a customer that is the current user.
    return o => o.Customer.ContactName ==
        HttpContext.Current.User.Identity.Name;
}

In diesem Beispiel wird eine Change-Interceptor-Methode für die Products-Entitätenmenge definiert. Diese Methode überprüft die Eingabe an den Dienst für einen Add-Vorgang oder Change-Vorgang und löst eine Ausnahme aus, wenn eine Änderung an einem ausgelaufenen Produkt vorgenommen wird. Sie blockiert außerdem das Löschen von Produkten als nicht unterstützten Vorgang.

' Define a change interceptor for the Products entity set.
<ChangeInterceptor("Products")> _
Public Sub OnChangeProducts(ByVal product As Product, _
                            ByVal operations As UpdateOperations)
    If operations = UpdateOperations.Change Then
        Dim entry As System.Data.Objects.ObjectStateEntry

        If Me.CurrentDataSource.ObjectStateManager _
            .TryGetObjectStateEntry(product, entry) Then

            ' Reject changes to a discontinued Product.
            ' Because the update is already made to the entity by the time the 
            ' change interceptor in invoked, check the original value of the Discontinued
            ' property in the state entry and reject the change if 'true'.
            If CType(entry.OriginalValues("Discontinued"), Boolean) Then
                Throw New DataServiceException(400, String.Format(
                            "A discontinued {0} cannot be modified.", product.ToString()))
            Else
                Throw New DataServiceException(String.Format( _
                    "The requested {0} could not be found in the data source.", product.ToString()))
            End If
        ElseIf (operations = UpdateOperations.Delete) Then
            ' Block the delete and instead set the Discontinued flag.
            Throw New DataServiceException(400, _
                "Products cannot be deleted; instead set the Discontinued flag to 'true'")
        End If
    End If
End Sub
// Define a change interceptor for the Products entity set.
[ChangeInterceptor("Products")]
public void OnChangeProducts(Product product, UpdateOperations operations)
{
    if (operations == UpdateOperations.Change)
    {
        System.Data.Objects.ObjectStateEntry entry;

        if (this.CurrentDataSource.ObjectStateManager
            .TryGetObjectStateEntry(product, out entry))
        {
            // Reject changes to a discontinued Product.
            // Because the update is already made to the entity by the time the 
            // change interceptor in invoked, check the original value of the Discontinued
            // property in the state entry and reject the change if 'true'.
            if ((bool)entry.OriginalValues["Discontinued"])
            {
                throw new DataServiceException(400, string.Format(
                            "A discontinued {0} cannot be modified.", product.ToString()));
            }
        }
        else
        {
            throw new DataServiceException(string.Format(
                "The requested {0} could not be found in the data source.", product.ToString()));
        }
    }
    else if (operations == UpdateOperations.Delete)
    {
        // Block the delete and instead set the Discontinued flag.
        throw new DataServiceException(400, 
            "Products cannot be deleted; instead set the Discontinued flag to 'true'"); 
    }
}

Siehe auch

Aufgaben

Gewusst wie: Definieren eines Dienstvorgangs (WCF Data Services)

Weitere Ressourcen

Definieren von WCF Data Services