传值

作者: 程序员潜规则 | 来源:发表于2020-04-03 01:01 被阅读0次

    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;

    using Microsoft.AspNetCore.Mvc.Filters;
    namespace Test
    {
    public class Startup
    {
    public Startup(IConfiguration configuration)
    {
    Configuration = configuration;
    }

        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        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.AddControllers();
            // cors
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });
    
            
    
        }
    
        // 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();
            }
            // cors
            app.UseCors("AllowAll"); 
            app.UseHttpsRedirection();
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
    

    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using System.Net;

    namespace Test.Controllers
    {
    [ApiController]
    [Route("api/[controller]")]
    //[Produces(MediaTypeNames.Application.Json)]
    public class WeatherForecastController : ControllerBase
    {
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        public People peo = new People {Pid = 123, PName = "sunjj"};
        private readonly ILogger<WeatherForecastController> _logger;
    
        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
    
        [HttpGet]
        public ActionResult Get()
        {
            return Ok("name");
        }
    
        [HttpGet("GetTestData/{id}")]
        public ActionResult<object> GetTwo(string id)
        {
            return Ok(new {
                value = id
            });
        }
    
        [HttpGet("GetThree")]
        public ActionResult<object> GetThree([FromQuery] int uid, [FromQuery] string name)
        {
            
            return Ok(new {
                id = uid,
                name = name
            });
        }
    
        [HttpGet("GetObject")]
        public People GetPeopleInfo()
        {
            return new People { Pid= 123, PName = "sunjj" };
        }
    
        [HttpPost("PostMethod")]
        public ActionResult<object> PostMethod([FromBody] UserInfo user)
        {
            return Ok(user);
        }
    
        [HttpPut("PutMethod")]
        public ActionResult<object> PutMethod([FromBody] UserInfo user)
        {
            return Ok(user);
        }
    
        
    }
    

    }
    import { Component, OnInit } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

    import { UserInfo } from 'src/Hero';
    import { userInfo } from 'os';
    import { join } from 'path';

    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit {
    heroesUrl = 'https://localhost:5001/api/weatherforecast/GetThree';
    herosPostUrl = 'https://localhost:5001/api/weatherforecast/PostMethod';
    heroPutUrl = 'https://localhost:5001/api/weatherforecast/PutMethod';

    title: string = 'my hero App';

    // httpOptions = {
    // headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
    // observe:'response',
    // params: new HttpParams({
    // uid: '1234',
    // name: ""
    // })
    // };

    constructor(private http: HttpClient) { }

    ngOnInit() {

    //this.getHttpInstance();
    //this.postHttpInstance();
    
    this.putMethod();
    

    }

    private putMethod() {
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    let body: any = JSON.stringify({ id: 20, name: 'Tornado', sex: 1, telephone: '123456789' });
    this.http.put<any>(this.heroPutUrl, body, { headers, observe: 'response' }).subscribe(data => {
    if (data.status === 200) {
    alert(data.body.telephone);
    }
    });
    }

    private postHttpInstance() {
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    let body: any = JSON.stringify({ id: 20, name: 'Tornado', sex: 1, telephone: '123456789' });
    this.http.post<any>(this.herosPostUrl, body, { headers, observe: 'response' }).subscribe(data => {
    if (data.status === 200) {
    alert(data.body.name);
    }
    });
    }

    private getHttpInstance() {
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    let params = new HttpParams();
    params = params.append('uid', '1001');
    params = params.append('name', 'sun');
    this.http.get<any>(this.heroesUrl, { headers, observe: 'body', params }).subscribe(data => {
    // if (data.status === 200) {
    // alert(data.body.id);
    // alert(data.body.name);
    // }
    if (data.id === 1001) {
    alert(data.id);
    }
    else {
    alert(data.id);
    }
    });
    }
    }

    相关文章

      网友评论

          本文标题:传值

          本文链接:https://www.haomeiwen.com/subject/fsgqphtx.html