HTML/AngularJS Frontend
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS HTTP OPTIONS Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="myController">
<h2>HTTP OPTIONS Example</h2>
<button ng-click="performOptionsRequest()">Perform OPTIONS Request</button>
<p>{{ optionsResponse }}</p>
</body>
</html>
AngularJS Frontend (JavaScript)
var app = angular.module('myApp', []);
app.controller('myController', function ($scope, $http) {
$scope.optionsResponse = '';
$scope.performOptionsRequest = function () {
$http({
method: 'OPTIONS',
url: 'https://ResourceController /api/resource'
})
.then(function (response) {
$scope.optionsResponse = 'Options Request Successful. Available methods: ' + response.headers('allow');
})
.catch(function (error) {
$scope.optionsResponse = 'Error performing OPTIONS request: ' + error.statusText;
});
};
});
C# Backend (Controller using ASP.NET Web API)
using System.Net;
using System.Net.Http;
using System.Web.Http;
public class ResourceController : ApiController
{
[HttpOptions]
[Route("api/resource")]
public HttpResponseMessage Options()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("Allow", "GET, POST, PUT, DELETE, OPTIONS");
// You can include additional headers as needed for your API
return response;
}
}
Conclusion
This example illustrated the utilization of the HTTP OPTIONS method in a C# API built with ASP.NET Web API. By responding to OPTIONS requests, the API communicates to clients the available HTTP methods for a specific resource.