傳值

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);
}
});
}
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容