SuperNuGetPackage 1.0.2
dotnet add package SuperNuGetPackage --version 1.0.2
NuGet\Install-Package SuperNuGetPackage -Version 1.0.2
<PackageReference Include="SuperNuGetPackage" Version="1.0.2" />
<PackageVersion Include="SuperNuGetPackage" Version="1.0.2" />
<PackageReference Include="SuperNuGetPackage" />
paket add SuperNuGetPackage --version 1.0.2
#r "nuget: SuperNuGetPackage, 1.0.2"
#:package SuperNuGetPackage@1.0.2
#addin nuget:?package=SuperNuGetPackage&version=1.0.2
#tool nuget:?package=SuperNuGetPackage&version=1.0.2
Backend (.NET) Final Exam
Make a MVC application with project name Task 1 and solution name BackendFinal.
Task 1 - Authentication mechanism
Create an application in which user can authenticate by username and password.
Create MVC application, then go to the Controllers folder and add another controller (Empty) named: SecurityController.cs
In this controller define action:
// SecurityController.cs
using Microsoft.AspNetCore.Mvc;
namespace Task1.Controllers
{
public class SecurityController : Controller
{
public IActionResult Login()
{
return View();
}
}
}
This action should load a form with two inputs for username and password. For that, go to the Views folder and create a subfolder named Security. In that subfolder, add a view (Empty) named Login. In this view add a form. This form method must only generate POST, so add it as a parameter to Html.BeginForm:
// Login.cshtml
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
@using (Html.BeginForm(FormMethod.Post))
{
<div>@ViewBag.Msg</div>
<div>
@Html.TextBox("UID")
</div>
<div>
@Html.Password("PWD")
</div>
<div>
<input type="submit" value="OK" />
</div>
}
Go to this address:
https://localhost:7061/Security/Login
Now we need another action in SecurityController.cs to process the submitted information. This method must be called only when the user submits (POST). This method must check if the username and password are correct:
- Hold in-memory dictionary of the usernames and passwords
- Add method which signs out the user
// SecurityController.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Task1.Controllers
{
public class SecurityController : Controller
{
public IActionResult Login()
{
return View();
}
// Dictionary to store users usernames and passwords
static Dictionary<string, string> users = new Dictionary<string, string>
{
{ "Michael", "1234" },
{ "John", "5678" }
};
// Method to authenticate the user
[HttpPost]
public IActionResult Login(string UID, string PWD)
{
if (users.ContainsKey(UID) && users[UID] == PWD)
{
var claims = new List<Claim> { new Claim(ClaimTypes.Name, UID) };
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
return RedirectToAction("Index", "Home");
}
else
{
ViewBag.ErrorMessage = "Incorrect username or password.";
return Login();
}
}
// Method to log out the user
public IActionResult Logout()
{
HttpContext.SignOutAsync().Wait();
return RedirectToAction("Login");
}
}
}
Enable authentication in Program.cs:
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
app.UseAuthorization();
app.UseAuthentication();
Log out URL:
https://localhost:7061/Security/Logout
Task 2
Create an ASP.NET Core Web API project named Task 2 and a Console App project named Task 2 Client.
Implement a method (e.g., squares) to calculate the sum of the squares of two numbers. These two numbers must be submitted using POST.
In Task 2 Web API Project:
Create MathController.cs:
// MathController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Task_2.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MathController : ControllerBase
{
[HttpPost]
public double Square([FromForm] double x, [FromForm] double y)
{
return x * x + y * y;
}
}
}
In Task 2 Console Client:
// Program.cs
var cnt = new HttpClient();
cnt.BaseAddress = new Uri("https://localhost:7065");
var content = new StringContent("X=3&Y=4", System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
var msg = cnt.PostAsync("/api/Math", content).Result;
if (msg.StatusCode == System.Net.HttpStatusCode.OK)
{
var result = msg.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
Task 3 � AJAX
Add MVC project named Task 3.
You are asked to call a server method using AJAX (GET method only). Server action must return a JSON object and it must be parsed using JavaScript and only partial data must be shown.
HomeController.cs
// HomeController.cs
public JsonResult Sum(double a, double b)
{
return Json(new { r = a + b });
}
Views/Home/Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<script type="text/javascript">
function okrun() {
var http = new XMLHttpRequest();
http.open("GET", "/Home/Sum?a=" + x.value + "&b=" + y.value, false);
http.send();
var h = JSON.parse(http.responseText);
alert(h.r);
}
</script>
<div>
<input type="number" id="x" />
<br/>
<input type="number" id="y" />
<br/>
<input type="button" value="ok" onclick="okrun();" />
</div>
Task 4 � WebSockets
Add MVC project named Task 4.
You must create an app that takes a string and returns the reversed string using WebSockets.
Views/Home/Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<div>
<input type="text" id="x" />
<br/>
<input type="button" value="send" onclick="sendclick();" />
</div>
<script type="text/javascript">
ws = new WebSocket("wss://localhost:7160/Home/Talk");
ws.onmessage = function(evt) { alert(evt.data.toString()); };
function sendclick() {
ws.send(x.value);
}
</script>
Enable WebSockets in Program.cs
app.UseStaticFiles();
app.UseWebSockets();
HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Net.WebSockets;
using Task_4.Models;
namespace Task_4.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public void Talk()
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
var sock = HttpContext.WebSockets.AcceptWebSocketAsync().Result;
DoTalking(sock);
}
}
void DoTalking(WebSocket sock)
{
var buffer = new byte[1024];
WebSocketReceiveResult n;
n = sock.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;
var info = System.Text.Encoding.UTF8.GetString(buffer, 0, n.Count);
var result = new String(info.Reverse().ToArray());
sock.SendAsync(new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(result)), WebSocketMessageType.Text, true, CancellationToken.None).Wait();
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|