Создан WebMethod в веб-формах:
[WebMethod]
public async Task<string> AuthenticateApi()
{
string json = new JavaScriptSerializer().Serialize(new
{
username = ConfigurationManager.AppSettings["username"].ToString(),
password = ConfigurationManager.AppSettings["password"].ToString()
});
string contents;
using (var client = new HttpClient())
{
var response = await client.PostAsync(ConfigurationManager.AppSettings["Url"].ToString(),
new StringContent(json, Encoding.UTF8, "application/json"));
contents = await response.Content.ReadAsStringAsync();
}
return contents;
}
Или вы также можете использовать HttpPost в MVC:
[HttpPost]
[AllowAnonymous]
public async Task<string> AuthenticateApi()
{
string json = new JavaScriptSerializer().Serialize(new
{
username = ConfigurationManager.AppSettings["username"].ToString(),
password = ConfigurationManager.AppSettings["password"].ToString()
});
var url = ConfigurationManager.AppSettings["Url"].ToString();
using (var client = new HttpClient())
{
var response = client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));
var contents = await response.Result.Content.ReadAsStringAsync();
return contents;
}
}
Затем вызвать Javascript следующим образом:
function authApi() {
return $.ajax({
url: '../AuthenticateApi',
method: 'POST',
dataType: 'json'
}).done(function (response) {
localStorage.setItem('AuthorizationData', JSON.stringify(response));