Friday, 10 March 2017

.aspcore web api cors





//ValuesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;

namespace WebApplication2.Controllers
{
    [EnableCors("AllowAll")]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
         List< people> people_list = new List<people> {
                new people {id =1,name="a",position="aa" },
                new people {id =2,name="b",position="bb" },
                new people {id =3,name="c",position="cc" },
                new people {id =4,name="d",position="dd" },
                new people {id =5,name="e",position="ee" },
                new people {id =6,name="f",position="ff" },
            };

        // GET api/values
        [HttpGet]
        public IEnumerable<people> Get()
        {
            return people_list;
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public people Get(int id)
        {
            return people_list.FirstOrDefault(x=>x.id==id);
        }

    }
}

-------------------------------------------------------------------

//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.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Cors.Infrastructure;

namespace WebApplication2
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();

            app.UseCors("AllowAll");
        }
    }
}

--------------------------------------------------------------------------

//project.json

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.AspNetCore.Cors": "1.1.1"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

----------------------------------------------------------------------------


//index.cshtml


<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">

    //var people_list = [];

    $(document).ready(function () {

        $.ajax({
            url: 'http://localhost:22222/api/values',
            type: 'GET',
            dataType: 'json',
            data: { },
            success: function (result) {

                //alert("success");
                $.each(result, function (index, value) {

                    $('#people_table').append('<tr>\
              <td>' + value.id + '</td>\
              <td>' + value.name + '</td>\
              <td>' + value.position + '</td></tr>');
                });
            },
            error: function () {
                alert("Error");
            }
        });
    });

</script>

<div>
    <table id="people_table" class="table table-striped">

        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Position</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

</div>

--------------------------------------------------------------------

change server to allow only origin from localhsot:12345, request is denied

//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.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Cors.Infrastructure;

namespace WebApplication2
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()));
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://localhost:12345"));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();

            //app.UseCors("AllowAll");
            app.UseCors( "AllowSpecificOrigin");
        }
    }
}

------------------------------------------

//webapi controller


namespace WebApplication2.Controllers
{
    //[EnableCors("AllowAll")]
    [EnableCors("AllowSpecificOrigin")]
    [Route("api/[controller]")]
    public class ValuesController : Controller

--------------------------------------------------------------------

request from localhost:12345 is accepted

reference:
http://stackoverflow.com/questions/29100538/how-do-you-enable-cross-origin-requests-cors-in-asp-net-5-mvc-6
https://docs.microsoft.com/en-us/aspnet/core/security/cors

No comments:

Post a Comment