我正在使用Web API 2.1,我已經成功地使用了CORS和UriPathExtensionMapping。但我想訪問我的API資源的查詢字符串參數以及即UriPathExtensionMapping Web API 2
http://example.com/test/api/Employee
http://example.com/test/api/Employee?id=10
http://example.com/test/api/Employee.json
http://example.com/test/api/Employee.xml
http://example.com/test/api/Employee.json?id=10
http://example.com/test/api/Employee.xml?id=10&name=someone
http://example.com/test/api/Employee.json?id=10&name=someone
上面提到的所有資源都是我希望他們使用的。我能夠使用1,2,3,4,但是在擴展和查詢字符串之後,它似乎不起作用。
以下是我的WebApiConfig.cs代碼。
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}",
defaults: new { }
);
config.Routes.MapHttpRoute(
name: "ApiUriPathExtension",
routeTemplate: "api/{controller}.{ext}",
defaults: new { ext = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
我在想什麼,任何幫助,非常感謝。
你能對你的意思吧'沒有詳細說明似乎沒有工作嗎?..如果你期望'id'的值來自查詢字符串,你不應該把它作爲路由模板的一部分,因爲路由模板在路由匹配期間不會查找查詢字符串。 .. – 2014-09-01 12:48:47
謝謝基蘭,我希望你回覆,你做到了。來到錯誤我得到「您正在尋找的資源已被刪除,名稱已更改,或暫時不可用。」我改變了上面的代碼與你的評論後,我實際上已經有了同樣的錯誤。 – Immortal 2014-09-01 12:52:37
另外我不僅有id,有時我還有一些其他查詢參數,如姓名,年齡等。我沒有將它作爲路由模板的一部分。事實上,我的api控制器中的方法/資源與參數有關,因此如果我將這些查詢字符串與上面的路由定義一起傳遞,我認爲它會起作用。 – Immortal 2014-09-01 12:55:03