2

I have a bunch of custom routes defined using AttributeRouting. I have a function in a controller that is trying to access one of these API functions at /api/GetBatchItems.

GetBatchItems is a function of the controller APIController, similar to:

[RouteArea("api")]
public sealed class APIController : ApiController{
    [GET("GetBatches")]
    public IEnumerable<PRAT.Models.EF.EFBatchItem> GetBatches() { ... }
}

In another controller, I am trying to get the result. When browsing directly everything is fine if I do it this way, but I want to be able to use my already defined route, is there a way to do that? I saw someone mention HttpAttributeRoutingConfiguration but I could not find that class anywhere. I don't want to have to use the MapHttpRoute method this way...

var config = new HttpConfiguration();
config.Routes.MapHttpRoute("default", "api/{controller}/{id}", null);

var server = new HttpServer(config);
var client = new HttpClient(server);

string url = Request.Url.GetLeftPart(UriPartial.Authority) + "/api/APIController/GetBatches";
var result = client.GetAsync(url).Result;
var content = result.Content;
var model = content.ReadAsAsync<IEnumerable<PRAT.Models.EF.EFBatchItem>>().Result;
if (model == null) return View();
else return View(model);
4

1 回答 1

1

使您的示例代码工作

您现有的代码示例需要进行两项更改才能工作:

  1. 使 {id} 可选,因为 GetBatches() 没有参数:

    config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
    
  2. 由于 HttpConfiguration 路由将 {controller} 匹配到名为 {controller}Controller 的类,请将您的 url 计算更改为:

    string url = Request.Url.GetLeftPart(UriPartial.Authority) + "/api/API/GetBatches";
    

更简单的版本

您可以使用现有路线 /api/GetBatches

var client = new HttpClient();

string url = Request.Url.GetLeftPart(UriPartial.Authority) + "/api/GetBatches";
var result = client.GetAsync(url).Result;
var content = result.Content;
var model = content.ReadAsAsync<IEnumerable<MyViewModel>>().Result;
if (model == null) return View();
else return View(model);

更简单(如果您不需要 HTTP)

用这个添加这个扩展类替换您的示例代码:

var model = (new APIController()).GetBatches();
if (model == null) return View();
else return View(model);
于 2013-06-17T21:11:23.017 回答