1

I have a web service that has an MVC controller and a WepAPI 2 controller.

The job of the MVC controller is to render and return HTML for a partial view. A different MVC application makes that call and then embeds the resulting HTML into its own page.

The partial view contains some controls that make calls to the WebAPI controller to temporarily store data. For this purpose I enabled session in the WebAPI controller using this code in Global.asax.cs:

protected void Application_PostAuthorizeRequest() {
    HttpContext.Current.SetSessionStateBehavior(
        System.Web.SessionState.SessionStateBehavior.Required);
}

When the calling application makes the call to the MVC controller, it passes a model to it. This model contains some initial data that the controls on the partial view need to display. This is the same kind of data the controls will create/update/delete using the WebAPI controller. I want to put the data from the model into the session so that the controls in the partial view would be able to read/update/delete this data.

My question is this: Is there any way to give the MVC controller access to the WepAPI session? Or is there any way to make the WebAPI controller use the same session as the MVC controller uses?

Daniel Gabriel
  • 3,939
  • 2
  • 26
  • 37
  • Try and avoid shoehorning state into your application like this - place the data you need to send to your ApiController into the view as hidden fields or data attributes so you can send them without relying on session state. – Ant P Jun 20 '14 at 19:11
  • I can't. The controls in the partial view are Kendo grids that rely on the server having CRUD methods. For the grids to work properly, I have to store the data on the server. – Daniel Gabriel Jun 20 '14 at 19:24
  • Check [http://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api](http://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api) – Zia Khan May 09 '16 at 06:26

1 Answers1

0

Add the following code in your Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    ...

    protected void Application_PostAuthorizeRequest()
    {
        if (IsWebApiRequest())
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

    private bool IsWebApiRequest()
    {
        return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
    }

}
Ε Г И І И О
  • 11,199
  • 1
  • 48
  • 63