0

I'm currently using ASP .NET MVC and Web API 2 in parallel in a project I'm working on.

I'd like to be able to include links to certain MVC Actions from within my API responses, as these actions often relate to the resources being provided.

The issue is that I have no MVC HttpContext from within Web API, so I cannot use the Url.Action method to generate links. My only other option is to manually/hard-code the links but I'd rather not take this approach as it doesn't scale.

Any way to spawn a MVC HttpContext/RequestContext?

Tito
  • 832
  • 10
  • 24

1 Answers1

2

You shouldn't consider mixing MVC/WebAPI because WebAPI is designed to be stateless, that's why its context is different than MVC.

If you need to use MVC links in WebAPI(just curious - why?), you should either use helpers like T4MVC or prepare your own, which encapsulate URLs to be used. You shouldn't ever consider using MVC context in WebAPI because you can never know what is its current state.

If API has to know something about your MVC structure, there is something wrong with your design IMO.

kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29
  • Interesting. In my case I am building a newer section of the site using client-side frameworks where all interaction is done via an API. The site is over 10 years old and has it's basis in MVC as well as older school ASP tech. The new section needs to link to older sections of the site hence this necessity. edit: I'd be curious to know why this would indicate something wrong with my design? – Tito Oct 02 '15 at 10:07
  • @Titus That's why you should have some kind of helpers, which will map URLs. Bringing context into WebAPI seems wrong for me. – kamil-mrzyglod Oct 02 '15 at 10:08
  • I agree, and won't be using that approach. I'm already introducing a lot of new tech to our stack so this may be something to sell later on down the line. For now I think I'll probably go with hard-coding the links. – Tito Oct 02 '15 at 10:11
  • On second thoughts, I think there's nothing wrong with spitting out MVC links within the API. I've found an answer to my question here: http://stackoverflow.com/questions/15250186/generating-route-url-to-mvc-controller-action-from-webapi – Tito Oct 05 '15 at 14:39
  • @Titus Depends on what do you expect from your API. If you think about reusing it, that approach is not a case. – kamil-mrzyglod Oct 05 '15 at 15:00