Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
.Net CORE Api Controller
Purpose
The purpose of this tutorial is to show an example of setting up an Api Controller (the approximate replacement to traditional web services such as ASMX) and making a request to the API Controller with C#.

API Service Controller:

/* This reads some server header data.  This CS file will be present in the Controllers folder of the project. */
namespace something.Controllers
{
	[ApiController]
	[Route("[controller]")]
	public class userDataController : ControllerBase
	{
		[HttpGet]
		// [IgnoreAntiForgeryToken]
		public async Task<ActionResult<userDataContainer>> Get()
		{
			string userData = "0";
			Microsoft.Extensions.Primitives.StringValues headerValues;
			if (Request.Headers.TryGetValue("somekey", out headerValues))
			{
				foreach (string entry in headerValues)
				{
					// Perform some sort of logic
					userData = entry;
				}
			}
			return userData;
		}
	}
}

/*
In this example, the code (below) is present in a separate CS file in the wwwroot of the website.  It is important to note that you can directly call an API Controller without this addition by having "api/controller-name" syntax in the URL.
If you elect to use this layout, in order for it to be recognized as tied to the API Controller, you would need to specify that in launchSettings.json.
*/
namespace something
{
	public class userDataContainer
	{
		public string userData { get; set; }
	}
}

/* launchSettings.json (only needed if you need to tie an API Controller to a "front-end" CS page) is found under the Properties folder of the project. */
{
	"Project-Name": {
		"commandName": "Project",
		"launchBrowser": true,
		"launchUrl: "userdata",
		"applicationUrl": "https://localhost:5001;http://localhost:5000",
		"environmentVariables": {
			"ASPNETCORE_ENVIRONMENT": "Development"
		}
	}
}


Requesting Data From The Api Controller:

using System.Text.Json;

public static string _UserLevel { get; set; }
public class UserDataContainer
{
	public string userData { get; set; }
}
public static async Task<UserDataContainer> GetUserData(string uri, string action)
{
	string fullUrl = uri + action;
	HttpClientHandler credHandler = new HttpClientHandler();
	credHandler.UseDefaultCredentials = true;
	var httpClient = new HttpClient(credHandler);
	using var httpResponse = await httpClient.GetAsync(fullUrl, HttpCompletionOption.ResponseHeadersRead);
	httpResponse.EnsureSuccessStatusCode();
	if (httpResponseContent is object && httpResponse.Content.Headers.ContentType.MediaType == "application/json")
	{
		var contentStream = await httpResponse.Content.ReadAsStreamAsync();
		UserDataContainer modeledData = await JsonSerializer.DeserializeAsync<UserDataContainer>(contentStream, new JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true});
		if (httpResponse.IsSuccessStatusCode)
		{
			_UserLevel = modeledData.userData.ToString();
		}
	}
	return null;
}


About Joe
Find Out Now!