如何将角度2应用程序的json数据发布到本地asp.net mvc webapi服务?

时间:2018-04-24 17:55:56

标签: sql-server

实际上我是成功从本地webapi服务获取数据,但发布数据尚未完成。请问我是否有任何发布数据的规则?。

这是我的Customer.component.ts文件代码

import { Component } from '@angular/core';
import { CustomerService} from '../Services/Customer.service';
import { ICustomer } from '../Models/Customer';
import 'rxjs/add/operator/map';

@Component({
    selector:'customer-list',
    templateUrl:'app/Templates/Customer.component.html',
    styleUrls:['app/StyleSheet/Customer.Component.css'],
    providers:[CustomerService]
})

export class CustomerComponent
{
    customers : ICustomer[];
    result: number
    data: ICustomer;
    constructor(private _customerService : CustomerService){
    }

    postData():void{
       this.data =  {Id:1,Name:"hai",AadharNumber:784512235689,Address:"hai",PhoneNumber:7894561230};
       this._customerService.postData(this.data).subscribe(cust=>this.result = Number(cust));
    }
    ngOnInit():void{
       this._customerService.getAllCustomers().subscribe(cust=>this.customers=cust);
    }
}

这是我的Customer.service.ts文件代码

import {Injectable} from '@angular/core';
import { ICustomer } from  '../Models/Customer';
import { Http,Response, RequestOptions, Headers} from '@angular/http' ;
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { JSONP_HOME } from '@angular/http/src/backends/browser_jsonp';

@Injectable()
export class CustomerService
{
    getserviceUrl : string="http://localhost:60769/api/Customer/AllCustomers";
    postServiceURL: string="http://localhost:60769/api/Customer/Insert";
    constructor(private _http:Http){}

   getAllCustomers(): Observable<ICustomer[]>{
       return this._http.get(this.getserviceUrl).map((response: Response)=><ICustomer[]> response.json());
   }
   postData(Customer:ICustomer): Observable<ICustomer>{
     var body = {"Id":"1","Name":"Hemarao","AadharNumber":"789456123012","Address":"SRIKAKULAM","PhoneNumber":"789456130"};
     let headers= new Headers({'Content-Type': 'application/json'});
     let options = new RequestOptions({headers: headers});
     var param = JSON.stringify(body);  

       return this._http.post(this.postServiceURL,param,options)
                .map((res: Response) => <ICustomer> res.json());
   }
} 

这是我当地的webapi解决方案Customer.cs文件代码

public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public long AadharNumber { get; set; }
        public long PhoneNumber { get; set; }
        public string Address { get; set; }
    }

这里是我的本地webapi解决方案CustomerApiController.cs文件代码

public class CustomerController : ApiController
    {
        [HttpGet]
       public List<Customer> AllCustomers()
        {
            return new List<Customer> { 
                new Customer { Id=101,Name="Murali Munna",AadharNumber=789456123012,Address="SRIKAKULAM", PhoneNumber=789456130},
                new Customer { Id=102,Name="Sivanagraj",AadharNumber=123045678956,Address="VIZIANAGARAM", PhoneNumber=1234567890},
                new Customer { Id=103,Name="Suresh",AadharNumber=123456789560,Address="VISAKHAPATNAM", PhoneNumber=8523697845},
                new Customer { Id=104,Name="Avinash",AadharNumber=85207410930,Address="EAST", PhoneNumber=5467891236},
                new Customer { Id=105,Name="SaiPrakash",AadharNumber=147852036956,Address="GUNTUR", PhoneNumber=7896541236}};
        }
        [HttpPost]
        public int Insert([FromBody]Customer customer)
        {
            return 1;
        }
        [HttpGet]
        public int Sample(string Name)
        {
            return 1;
        }
    }

在这里,我已将下面的代码放在web.config文件中

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:3000"></add>
        <add name="Access-Control-Allow-Headers" value="Content-Type, application/json"></add>
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT, DELETE,OPTIONS"></add>
      </customHeaders>
    </httpProtocol>

1 个答案:

答案 0 :(得分:0)

其中一条规则确实允许某些https调用通过配置cors来访问webapi。我暂时允许所有来电访问webapi,如下所示:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            var corsAttr = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(corsAttr);

接下来和你已经做的类似,正在创建webapi,这样的事情应该可行

        [ResponseType(typeof(CustomerDto))]
        public IHttpActionResult PostCustomer(CustomerDto Customer)
        {
            var _unitofwork = UnityConfig.GetConfiguredContainer().Resolve<DalUnitOfWork>();
            var customer = ModelFactory.CreateCustomer(Customer);
            _unitofwork.CustomerRepo.Add(customer);
            _unitofwork.Commit();
            return Ok(new ClientMessage("Customer added.", string.Format("The customer {0} has been saved towards the database", Customer.Name), ClientMessageSeverity.success));
        }

为了与服务器通信,我更喜欢使用Httpclient并使用observable(可能是一些更清晰的代码)。代码看起来像这样

import { Component, ViewChild, Input, OnInit, Injectable, Injector } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { URLSearchParams, QueryEncoder,Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';

@Injectable()
export class CustomerserviceService {
    constructor(private http: HttpClient,private httpold: Http, private notificationService: NotificationsService, private databaseservice: DatabaseServiceIsbusy) {       
    }

    private baseUrlTask = 'http://localhost:45258/customer'

    private httpOptions = {
        headers: new HttpHeaders({ 
          'Access-Control-Allow-Origin':'*',
          'Content-Type': 'application/json',
        })
      };

     public addCustomer(customer: ICustomer):Observable<IClientmessage>{
        return this.http.post<IClientmessage>(this.baseUrlTask, customer,this.httpOptions).catch(error =>this.handleError(error));;
    }