发布httpclient angular 5和C#webapi

时间:2018-02-18 13:20:08

标签: post asp.net-web-api angular5

我使用httpclient和post方法将对象发送到C#web api。这在当地工作得很好。但是在服务器上它会出错。

我在service.ts中的post方法就像....

 <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>



    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

在compoenent.ts文件中,我正在拨打以下电话......

post(url:string, data): Observable<any> {
    // console.log(data);
    //Construct URL
    let URL = this.APIURL + url;                      
    return this.http.post(URL, data)               
            .map(
                (response: HttpResponse<any>) => {                       
                        const data = response;
                        return data;                        
                }                   
            )
            .catch(this.handleError.bind(this));                
  }

这在本地工作正常,但是一旦我在测试服务器上部署api和我的应用程序,它就会出现错误的错误&#39; 500内部服务器错误&#39;。当我看到&#39; Network&#39;选项卡,它会出现异常错误,

const newprod = { "proid": form['prodid'], "prodDescription": form['prodDescription'] };

this.myService.post('Products/PostProduct', newprod)
    .subscribe((data: string[]) => { 
 --- other code ----
 });

1 个答案:

答案 0 :(得分:0)

使用竖线来映射响应...

import {map} form 'rxjs/operators';

...
public getSomeData() {
    this.httpClient.post(BASE_URL + 'api/SomeTest/SomeAction', {'some_conf': 123})
        .pipe(
            map(res: any => {/* todo */ return res.json();}));
}

则...

service.getSomeData()
    .subscribe(...

或者可能需要使用一些标题......

// tslint:disable-next-line
let headers = new HttpClient();
headers.set('Content-Type', 'text/plain; charset=utf-8');
// some auth params, tokens maybe need
this.httpClient
    .post(
        BASE_URL + 'api/SomeTest/SomeAction', 
        JSON.stringify( {'some_conf': 123} ), 
        { headers: headers })
    .pipe(...

在c#api ...

public class SomeTestController: ApiController
{
    [Route("api/SomeTest/SomeAction")]
    public async Task<IHttpActionResult> SomeAction(int some_conf) 
    {
        // todo ...
    }

或者...

// maybe some auth
[Authorize(Roles = "admin,moderator")]
[Route("api/SomeTest/SomeAction")]
public async Task<IHttpActionResult> SomeAction([FormBody]string body_text)
{
    // todo ...
}

添加Web Api路由器配置,一些支持的格式

...
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
    new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
    new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain"));

试试这个......