1

I have two API controllers located in two different folders which has GetEvents() action:

V1
  EventsController

V2
  EventsController

I'd like to be able to access the controllers using:

 api/v1/events and api/v2/events

my route template looks like this

api/v{version}/{controller}

private static string GetRequestVersion(HttpRequestMessage request) {

// how to find the {version} value from url?

}

I've written a code using REGEX which works fine:

 private static string ExtractVersionFromUrl(HttpRequestMessage request)
        {
            Match match = Regex.Match(request.RequestUri.PathAndQuery, @"/v(?<version>\d+)/", RegexOptions.IgnoreCase);

            return match.Success ? match.Groups["version"].Value : null;
        }

What's the standard approach to retreive such data from uri?

4

2 に答える 2

0

戻り値に関する推測を危険にさらしています。これを行う別の方法は、コントローラーのメソッドのパラメーターとして次のように定義するだけです。

public IEnumerable<Event> GetEvents(string version, HttpRequestMessage request) {
...
}

私はこれを自分で理解しました。Web API はとにかく美しい!

于 2013-08-23T04:09:41.690 に答える