Condividi tramite


Procedura: intercettare messaggi del servizio dati (WCF Data Services)

Con WCF Data Services è possibile intercettare i messaggi di richiesta per l'aggiunta di logica personalizzata a un'operazione. Per intercettare un messaggio, si utilizzano metodi attribuiti in modo speciale nel servizio dati. Per ulteriori informazioni, vedere Intercettori (WCF Data Services).

Nell'esempio riportato in questo argomento viene utilizzato il servizio dati Northwind di esempio. Questo servizio viene creato al completamento della Guida rapida di WCF Data Services.

Per definire un intercettore di query per il set di entità Orders

  1. Nel progetto del servizio dati Northwind aprire il file Northwind.svc.

  2. Nella tabella codici per la classe Northwind aggiungere l'istruzione using riportata di seguito (Imports in Visual Basic).

    Imports System.Linq.Expressions
    
    using System.Linq.Expressions;
    
  3. Nella classe Northwind definire un metodo dell'operazione del servizio denominato OnQueryOrders nel modo seguente:

    ' 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()
    

Per definire un intercettore di modifiche per il set di entità Products

  1. Nel progetto del servizio dati Northwind aprire il file Northwind.svc.

  2. Nella classe Northwind definire un metodo dell'operazione del servizio denominato OnChangeProducts nel modo seguente:

    ' 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)
    

Esempio

In questo esempio viene definito un metodo intercettore di query per il set di entità Orders che restituisce un'espressione lambda. Questa espressione contiene un delegato che filtra gli Orders richiesti in base ai Customers correlati che presentano un nome di contatto specifico. Il nome viene a sua volta determinato in base all'utente che lo richiede. In questo esempio si presuppone che il servizio dati sia ospitato all'interno di un'applicazione Web ASP.NET che utilizza WCF e che l'autenticazione è abilitata. La classe HttpContext viene utilizzata per recuperare il principio della richiesta corrente.

' 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 questo esempio viene definito un metodo intercettore di modifiche per il set di entità Products. Questo metodo convalida l'input per il servizio per un'operazione Add o Change e genera un'eccezione quando una modifica viene apportata a un prodotto non più disponibile. Blocca inoltre l'eliminazione di prodotti come operazione non supportata.

' 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'"); 
    }
}

Vedere anche

Attivitá

Procedura: definire un'operazione del servizio (WCF Data Services)

Altre risorse

Servizio dati (WCF Data Services)