3

同じ変数名のデータ型に基づいて、コントローラーでエンドポイントを拡張したいと考えています。たとえば、メソッド A は int を受け取り、メソッド B は文字列を受け取ります。新しいルートを宣言するのではなく、ルーティング メカニズムで int と文字列を区別する必要があります。これが私の言いたいことの例です。

「ApiControllers」のセットアップ:

public class BaseApiController: ApiController
{
        [HttpGet]
        [Route("{controller}/{id:int}")]
        public HttpResponseMessage GetEntity(int id){}
}

public class StringBaseApiController: BaseApiController
{

        [HttpGet]
        [Route("{controller}/{id:string}")]
        public HttpResponseMessage GetEntity(string id){}
}

「WebApionfig.cs」には、次のルートが追加されています。

config.Routes.MapHttpRoute(
    "DefaultApi",
    "{controller}/{id}",
    new { id = RouteParameter.Optional }
);

"http://controller/1"呼び出して結果を取得したい"http://controller/one"。代わりに、複数ルートの例外が表示されます。

4

2 に答える 2

1

以下の解決策を試すことができます。

//Solution #1: If the string (id) has any numeric, it will not be caught.
//Only alphabets will be caught
public class StringBaseApiController: BaseApiController
{
 [HttpGet]
 [Route("{id:alpha}")]
 public HttpResponseMessage GetEntity(string id){}
}
//Solution #2: If a seperate route for {id:Int} is already defined, then anything other than Integer will be caught here.
public class StringBaseApiController: BaseApiController
{
 [HttpGet]
 [Route("{id}")]
 public HttpResponseMessage GetEntity(string id){}
}
于 2018-04-20T17:29:18.497 に答える
-2

文字列のみを使用し、int、文字列、またはその他のものを取得したかどうかを内部で確認し、適切なメソッドを呼び出します。

public class StringBaseApiController: BaseApiController
{

        [HttpGet]
        [Route("{controller}/{id:string}")]
        public HttpResponseMessage GetEntity(string id)
        {
            int a;
            if(int.TryParse(id, out a))
            {
                return GetByInt(a);
            }
            return GetByString(id);
        }

}
于 2014-10-28T16:52:19.500 に答える