- โปรเจ็กส์ WebApi
- โปรเจ็กส์ WebApp
- ทำการ Enable CORS
สร้างโปรเจ็กส์ WebApi และ WebApp มาทดสอบ
1.โปรเจ็กส์ WebApi
ที่ไฟล์ Controllers/WeatherForecastController.cs เพิ่มเมธอด GetWeatherForecast(int id)
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace WebApi1.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } // GET: WeatherForecast/5 [HttpGet("{id}")] public ActionResult<WeatherForecast> GetWeatherForecast(int id) { var rng = new Random(); return new WeatherForecast { Date = DateTime.Now.AddDays(0), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }; } } }
ทดลองเรียกที่ https://localhost:44305/weatherforecast/1 จะได้
{ "date": "2019-11-13T16:27:20.0042835+07:00", "temperatureC": 31, "temperatureF": 87, "summary": "Hot" }
2.โปรเจ็กส์ WebApp
ที่ไฟล์ Shared/_Layout.cshtml เพิ่มการเรียกใช้ jQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - WebApp2</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> ...
ที่ไฟล์ Pages/Index.cshtml เพิ่ม Button1 และ Script
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> <input id="Button1" type="button" value="Click Me!"/> </div> <script type="text/javascript"> $(document).ready(function () { $("#Button1").click(function () { $.ajax({ type: "GET", url: 'http://localhost:44305/weatherforecast/1', success: function (data) { var items = []; $.each(data, function (key, val) { items.push("key='" + key + "',value='" + val + "'"); }); console.log(items); alert(items); }, failure: function (errMsg) { alert(errMsg); } }); }); }); </script>
ทดลองรันและกดปุ่ม จะได้
Access to XMLHttpRequest at 'https://localhost:44305/weatherforecast/1' from origin 'http://localhost:49934' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
3.ทำการ Enable CORS
ที่โปรเจ็กส์ WebApi แก้ไขไฟล์ Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WebApi1 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } readonly string MyPolicyName = "_MyPolicyName"; public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(MyPolicyName, builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors(MyPolicyName); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
บรรทัดที่ 35 CorsPolicyBuilder.AllowAnyOrigin ยอมให้เรียกใช้ได้จากทุกที่
รัน WebApp แล้วกดปุ่มอีกที ก็จะเรียกได้ละ
["key='date',value='2019-11-13T16:32:02.5259412+07:00'", "key='temperatureC',value='4'", "key='temperatureF',value='39'", "key='summary',value='Scorching'"]
Link