0

I am using web api in my mvc application. I have method in web api which returns user detail using userId (which is in session["userID"])

public object getUserDetail()
{
  //here is need of session["userID"]
  // return somthing
}

so what is best way to access this web api method from jquery . Should i access this directly or first i should call my controller method and from there i should call this web api method.

satyender
  • 817
  • 4
  • 12
  • 27

4 Answers4

0

WebApi is already an exposed endpoint for you to access your data from. Going to your controller, and calling the method from there diminishes the intent of having exposed the method as an Api in the first place. Try making a call to the route of the Api method, and you should be fine.

On a side note, try exposing a strongly typed object instead of just returning an object.

sameerfair
  • 406
  • 7
  • 13
0

You can directly call WebApi from jquery for performing operations(like insert/update/delete)other than returning JSON for processing back. For the scenarios where you require manipulating your view, call mvc controller which calls the Webapi. So, for your case, the getUserDetail() method returns data. If these return values needs to be used in your view, then call it from mvc controller

Karthik M R
  • 980
  • 1
  • 7
  • 12
0

what is best way to access this web api method from jquery

Simply make an ajax call.

   var url = www.example.com/api/user;
   $.ajax({
        type: 'GET',
        url: url,
        success: function(userValue) {
            // Do something with your user info...
        },
        error: function(error) {
           // Something went wrong. Handle error.
        }
    });

And have your controller return the value.

public class UserController : ApiController
{
    [HttpGet] // For clarity only
    public object Get()
    {
        // return your object.
        return session["userID"];
    }
}

And to get your url for the controller, you can use this in your view.

Url.HttpRouteUrl("DefaultApi", new {controller = "UserController "})})

Where DefaultApi is the route name defined in your route table (usually in RouteConfig.cs).

Edit:

Regarding access to session there's a number of ways to get around it. Take a look at this question and I think you will solve it. Accessing Session Using ASP.NET Web API

Or this tutorial: http://www.codeproject.com/Tips/513522/Providing-session-state-in-ASP-NET-WebAPI

public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState 
{
    public SessionableControllerHandler(RouteData routeData)
        : base(routeData)
    {}
} 

public class SessionStateRouteHandler : IRouteHandler 
{ 
    IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
    {
       return new SessionableControllerHandler(requestContext.RouteData);
    }
}

And lastly register it with your route:

RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
).RouteHandler = new SessionStateRouteHandler();  

Or add this to your Global.asax.cs

protected void Application_PostAuthorizeRequest() 
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Community
  • 1
  • 1
smoksnes
  • 10,509
  • 4
  • 49
  • 74
0

Feels like you might want to step back and rethink the basics. The main question here is: does it sound right that one view layer (MVC) calls another view layer (web api)? And simple answer is: no.

Usual setup is that your ajax calls target your Web Api controller methods directly. But if for whatever reason you find yourself thinking that you really need your MVC to call WebApi then that looks for extracting business logic to separate layer/tier so what you end up with is both, MVC and Web API, calling same method in separate class/layer (whatever your methods actually do).

So, instead of:

    //this is in your MVC controller
    public ActionResult SomeMVCAction(){
    MyWebApiMethod();
    }

    //This is in your web api controller
    public SomeStrongType MyWebApiMethod(){
    var sum = 2+2;
    }

you might want to have something like:

//this is in your MVC controller
public ActionResult SomeMVCAction(){
DoSum();
}



//This is in your web api controller
public SomeStrongType MyWebApiMethod(){
DoSum()
}

///This function is defined in separate layer/project which is your business layer
public static int DoSum(){
return 2+2;
}

PS. Regarding session...There is a reason why session is not (easily) accessible in WebApi. REST Api should be stateless so you might want to rethink your design where you need session in web api controller. You can describe a problem you're trying to solve by accessing session in web api controller and then we can try to give opinion on that.

dee zg
  • 13,793
  • 10
  • 42
  • 82