Asked  7 Months ago    Answers:  5   Viewed   33 times

I realize session and REST don't exactly go hand in hand but is it not possible to access session state using the new Web API? HttpContext.Current.Session is always null.




For an MVC project make the following changes (WebForms and Dot Net Core answer down below):


public static class WebApiConfig
    public static string UrlPrefix         { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

    public static void Register(HttpConfiguration config)
            name: "DefaultApi",
            routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }


public class MvcApplication : System.Web.HttpApplication

    protected void Application_PostAuthorizeRequest()
        if (IsWebApiRequest())

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


This solution has the added bonus that we can fetch the base URL in javascript for making the AJAX calls:



    <script type="text/javascript">
        var apiBaseUrl = '@Url.Content(ProjectNameSpace.WebApiConfig.UrlPrefixRelative)';

    @RenderSection("scripts", required: false) 

and then within our Javascript files/code we can make our webapi calls that can access the session:

$.getJSON(apiBaseUrl + '/MyApi')
   .done(function (data) {
       alert('session data received: ' + data.whatever);


Do the above but change the WebApiConfig.Register function to take a RouteCollection instead:

public static void Register(RouteCollection routes)
        name: "DefaultApi",
        routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }

And then call the following in Application_Start:


Dot Net Core

Add the Microsoft.AspNetCore.Session NuGet package and then make the following code changes:


Call the AddDistributedMemoryCache and AddSession methods on the services object within the ConfigureServices function:

public void ConfigureServices(IServiceCollection services)


and in the Configure function add a call to UseSession:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)


Within your controller, add a using statement at the top:

using Microsoft.AspNetCore.Http;

and then use the HttpContext.Session object within your code like so:

    public IActionResult setsession(string data)
        HttpContext.Session.SetString("keyname", data);
        return Ok("session data set");

    public IActionResult getsessiondata()
        var sessionData = HttpContext.Session.GetString("keyname");
        return Ok(sessionData);

you should now be able to hit:


and then going to this URL will pull it out:


Plenty more info on accessing session data within dot net core here:

Performance Concerns

Read Simon Weaver's answer below regarding performance. If you're accessing session data inside a WebApi project it can have very serious performance consequence - I have seen ASP.NET enforce a 200ms delay for concurrent requests. This could add up and become disastrous if you have many concurrent requests.

Security Concerns

Make sure you are locking down resources per user - an authenticated user shouldn't be able to retrieve data from your WebApi that they don't have access to.

Read Microsoft's article on Authentication and Authorization in ASP.NET Web API -

Read Microsoft's article on avoiding Cross-Site Request Forgery hack attacks. (In short, check out the AntiForgery.Validate method) -

Tuesday, June 1, 2021
answered 7 Months ago

That happens because you are not actually returning a List<Employee> but an object (EmployeeList) that has a List<Employee> in it.
Change that to return Employee[] (an array of Employee) or a mere List<Employee> without the class surrounding it

Friday, August 6, 2021
Andras Zoltan
answered 4 Months ago

The MVC Web API documentation feature walks through your API classes and methods using reflection. This will build the structure of the documentation but will result in more or less empty (and useless) documentation unless you have added documentation comments.

The body of the documentation is filled using the XML file that is generated using /// documentation comments which has a specific structure that must be followed. That means that you can't fill your xml with whatever you want it to display, it actually has to be connected to something that is in your API and must follow the structure of your classes and properties.

So in your case you can't put model property documentation in an api method. You have to put it into the Model where the property exists.


  public class TestModel
  /// <summary>This is the first name </summary>
      property String FirstName {get;set;}
  /// <summary>This is the surname</summary>
      property String Surname {get; set;}
      property Boolean Active {get;set;} 


  /// <summary>
  /// This is a test action
  /// </summary>
  /// <param name="model">this is the model</param> 
  public HttpResponseMessage Post(my.namespace.models.TestModel model)

Modify Help Pages

The default Help pages that are automatically generated do not include Model documentation only the api methods are documented. In order to display more information about the parameters in your api a customisation is required. The instruction that follow are one way to add parameter documentation.

Create two new types in Areas/HelpPage/Models

public class TypeDocumentation
    public TypeDocumentation()
        PropertyDocumentation = new Collection<PropertyDocumentation>();

    public string Summary { get; set; }
    public ICollection<PropertyDocumentation> PropertyDocumentation { get; set; } 

public class PropertyDocumentation
    public PropertyDocumentation(string name, string type, string docs)
        Name = name;
        Type = type;
        Documentation = docs;
    public string Name { get; set; }
    public string Type { get; set; }
    public string Documentation { get; set; }

Add a new property to HelpPageApiModel.cs

public IDictionary<string, TypeDocumentation> ParameterModels{ get; set; } 

Create a new interface

internal interface IModelDocumentationProvider
    IDictionary<string, TypeDocumentation> GetModelDocumentation(HttpActionDescriptor actionDescriptor);

Modify XmlDocumentationProvider to implement the new interface

public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider
    private const string TypeExpression = "/doc/members/member[@name='T:{0}']";
    private const string PropertyExpression = "/doc/members/member[@name='P:{0}']";
///... existing code

    private static string GetPropertyName(PropertyInfo property)
        string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", property.DeclaringType.FullName, property.Name);
        return name;

    public IDictionary<string, TypeDocumentation> GetModelDocumentation(HttpActionDescriptor actionDescriptor)
        var retDictionary = new Dictionary<string, TypeDocumentation>();
        ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
        if (reflectedActionDescriptor != null)
            foreach (var parameterDescriptor in reflectedActionDescriptor.GetParameters())
                if (!parameterDescriptor.ParameterType.IsValueType)
                    TypeDocumentation typeDocs = new TypeDocumentation();

                    string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, GetTypeName(parameterDescriptor.ParameterType));
                    var typeNode = _documentNavigator.SelectSingleNode(selectExpression);

                    if (typeNode != null)
                        XPathNavigator summaryNode;
                        summaryNode = typeNode.SelectSingleNode("summary");
                        if (summaryNode != null)
                            typeDocs.Summary = summaryNode.Value;

                    foreach (var prop in parameterDescriptor.ParameterType.GetProperties())
                        string propName = prop.Name;
                        string propDocs = string.Empty;
                        string propExpression = String.Format(CultureInfo.InvariantCulture, PropertyExpression, GetPropertyName(prop));
                        var propNode = _documentNavigator.SelectSingleNode(propExpression);
                        if (propNode != null)
                            XPathNavigator summaryNode;
                            summaryNode = propNode.SelectSingleNode("summary");
                            if (summaryNode != null) propDocs = summaryNode.Value;
                        typeDocs.PropertyDocumentation.Add(new PropertyDocumentation(propName, prop.PropertyType.Name, propDocs));

                    retDictionary.Add(parameterDescriptor.ParameterName, typeDocs);



        return retDictionary;

Add code to HelpPageConfigurationExtension in GenerateApiModel method

IModelDocumentationProvider modelProvider =
            config.Services.GetDocumentationProvider() as IModelDocumentationProvider;
if (modelProvider != null)
    apiModel.ParameterModels = modelProvider.GetModelDocumentation(apiDescription.ActionDescriptor);

Modify HelpPageApiModel.cshtml adding to following where you want the Model documentation to be displayed.

bool hasModels = Model.ParameterModels.Count > 0;
if (hasModels)
     <h2>Parameter Information</h2>
  @Html.DisplayFor(apiModel => apiModel.ParameterModels, "Models")


Add a Models.cshtml to DisplayTemplates

@using System.Web.Http
@using System.Web.Http.Description
@using MvcApplication2.Areas.HelpPage.Models
@model IDictionary<string, TypeDocumentation>

@foreach (var modelType in Model)
    if (modelType.Value.Summary != null)
    <table class="help-page-table">

            @foreach (var propInfo in modelType.Value.PropertyDocumentation)
                    <td class="parameter-name"><b>@propInfo.Name</b> (@propInfo.Type)</td>

                    <td class="parameter-documentation">
Thursday, September 9, 2021
answered 3 Months ago

Thank you for all the help. :)

I did some research myself during the last few months and I learnt a lot about the identity management stuff. Many of that also thanks to the guys from IdentityServer (and their other projects).

What I finally did was the following (very briefly):

  • IdentityServer is used as a provider for all client applications. The cookie and OIDC middleware are used.
  • I used the ASP.NET Identity user service to store the users in an SQL Server database. (The IdentityServer configuration is by the way also stored in a database.)
  • I set up a Web API service that uses the ASP.NET Identity user manager for user configuration (change password, create new users, ...). It uses bearer authentication with the application with IdentityServer as provider.
  • As a side note, IdentityManager is used as an internal admin tool to manage all the users.

If anyone is looking for some help setting up his / her identity management system (and thinks I can help): please ask. ;)

Thursday, October 21, 2021
Desmond Hume
answered 2 Months ago

Under the hood, Web Api supports Content Negotiation mechanism to automatically opt the correct formatter based on the header Content-Type in HTTP request.

By default content negotiation supports three formatters: json, xml and form-urlencoded data. If no formatter found, client will receives HTTP error 406 (Not Acceptable).

See more:

If you need to allow Web Api support another Content-Type, you can write your own custom formatter:

Wednesday, November 3, 2021
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :