0

私はこのようなサービス契約を結んでいます:

[WebGet(UriTemplate = "getdata?key={key}&format={format}")]
Event[] GetIncidentsXml(string key, string format);

コードでは、次のように応答形式を切り替えています。

var selectedFormat = ParseWebMessageFormat(format);
WebOperationContext.Current.OutgoingResponse.Format = selectedFormat;

(ParseWebMessageFormatは、型の列挙型解析をまとめるメソッドです)

この部分は期待どおりに機能し、渡されたパラメーターに応じてXMLまたはJSONのいずれかを取得します。

それが落ちるのは、私が例外をスローしたときです。渡された(API)キーが無効な場合、私はこれを行っています:

var exception = new ServiceResponse
{
    State = "fail", 
    ErrorCode = new ErrorDetail { Code = "100", Msg = "Invalid Key" }
};

throw new WebProtocolException(HttpStatusCode.BadRequest, "Invalid Key.", exception, null);

例外がスローされた場合、戻りタイプは常にXMLです。

<ServiceResponse xmlns="http://schemas.datacontract.org/2004/07/IBI.ATIS.Web.ServiceExceptions" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ErrorCode>
        <Code>100</Code>
        <Msg>Invalid Key</Msg>
    </ErrorCode>
    <State>fail</State>
</ServiceResponse>

リターンタイプの変更は、サービスメソッドのコードの最初の行であるため、例外がスローされる前に発生します。

要求形式に基づいて型を返すようにWCFを設定できることは知っていますが、クエリ文字列を介して渡された型を使用する必要があります。

自動メッセージタイプはconfigでオフになっています:

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" />
4

1 に答える 1

0

何らかの方法でデフォルトの応答形式を指定する必要があるためです。表示されている動作は標準です。特定のヘッダーを調べて、応答形式を決定する必要があります。次に、要求インターセプターを実装して、送信応答の形式がどのようなものである必要があるかを把握できます。

したがって、あなたの質問に答えるには、何も言及されていない場合はデフォルトのフォーマットタイプを使用するか、不適切なリクエストを返す必要があります. REST は、SOAP とは異なり、プロトコルというよりもパラダイムです。

更新:明確にするために。このようなことができます。

[ServiceContract()]
public interface ICustomerService
{
   [OperationContract]
   [WebGet(UriTemplate ="?format={formatType}",BodyStyle = WebMessageBodyStyle.Bare)]
   IResponseMessage GetEmCustomers(string formatType);

}

public class CustomerService : ServiceBase
{
  IResponseMessage GetEmCustomers(string formatType)
  {
    try
    {
      var isValid  = base.validateformatspecification(formatType);// check to see if format is valid and supported
      if(!isValid) return base.RespondWithError(formatType,new Error {Msg= "Dude we dont support this format"});
      var customers = CustomerProvider.GetAll();
      return base.Respond(formatType,customer);// This method will format the customers in desired format,set correct status codes and respond.
    }catch(Exception ex)
    {
      // log stuff and do whatever you want
      return base.RespondWithError(formatType,new Error{Msg = "Aaah man! Sorry something blew up"});// This method will format the customers in desired format,set correct status codes and respond.

    }      
  }    
}

public class ServiceBase
{
  public IResponseMessage Respond<T>(string format,T entity);
  public IResponseMessage RespondWithError<T>(string format, T errorObject);

}

public class Error:IResponseMessage {/*Implementation*/}

public class GetEmCustomerResponseResource:List<Customer>,IResponseMessage {/* Implementation*/}

public class GetEmCustomerErrorResponse: IResponseMessage {/* Implementation   */}
于 2012-05-07T16:06:23.070 に答える