I have an API secured by a bearer token. The API has two controllers, one is the default WeatherForecast
and the second one is for handling CRUD operations for player model. I decided to get my token from WeatherForecast
and use it to call player in my MVC project.
But when I start debugging, it shows Unauthorized for response in every MVC action. It's ok on using postman though.
Here are the controller methods for HttpGet
and HttpPost
:
namespace MyMVCProject.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IHttpClientFactory _clientFactory;
public HomeController(ILogger<HomeController> logger, IHttpClientFactory clientFactory)
{
_logger = logger;
_clientFactory = clientFactory;
}
public async Task<IActionResult> Index()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/weatherforecast/");
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string token = await response.Content.ReadAsStringAsync();
HttpContext.Session.SetString("JwtToken", token);
}
return View();
}
public async Task<IActionResult> GetAllPlayers()
{
var accessToken = HttpContext.Session.GetString("JwtToken");
List<Player> players = new List<Player>();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/api/player");
var client = _clientFactory.CreateClient();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var apiString = await response.Content.ReadAsStringAsync();
players = JsonConvert.DeserializeObject<List<Player>>(apiString);
}
return View(players);
}
[HttpPost]
public async Task<IActionResult> AddPlayer(Player player)
{
var accessToken = HttpContext.Session.GetString("JwtToken");
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:42045/api/player/");
if (player != null)
{
request.Content = new StringContent(JsonConvert.SerializeObject(player), System.Text.Encoding.UTF8, "application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
else
{
return BadRequest();
}
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
var apiString = await response.Content.ReadAsStringAsync();
player = JsonConvert.DeserializeObject<Player>(apiString);
TempData["success"] = "Player Added Successfully!";
}
else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
TempData["badrequest"] = "Player with the same name already exists";
}
return View(player);
}
}
}
CodePudding user response:
HttpRequestMessage
has a Headers property of type HttpRequestHeaders
. This class has two Add
methods you can use.
You can add headers like this:
request.Headers.Add("Authorization", "Bearer " YourToken);
CodePudding user response:
I am using this syntax
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);