Aurelia获取客户端 - 不支持的媒体类型 - .NET Core WebAPI

时间:2017-02-18 15:52:48

标签: .net asp.net-core .net-core aurelia aurelia-fetch-client

当我尝试使用Aurelia Fetch Client将两个参数作为JSON发布到.NET Core WebAPI时,我得到:415 (Unsupported Media Type)

的ApplicationController

[HttpPost("getapplications")]
public ApplicationViewModel GetApplications([FromBody] ApplicationSearchModel model)
{
    var applications = _applicationService.GetApplications().ToList();

    return new ApplicationViewModel()
    {
        Applications = applications
    };
}

public class ApplicationSearchModel
{
    public DateTime? From { get; set; }

    public DateTime? To { get; set; }
}

的application.js

import { inject } from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';

@inject(HttpClient)

export class Application {
  constructor(httpClient) {
    this.applications = [];

    this.httpClient = httpClient;
  }

  getApplications() {
    this.httpClient.fetch("http://localhost:9001/api/application/getapplications", {
      method: "POST",
      body: JSON.stringify({
        From: '2017-02-18',
        To: '2017-02-18'
      }),
        headers: {
        "content-type": "application/json; charset=utf-8" //Tried without headers aswell
      }
    });
  }

  activate(params) {
    this.getApplications();
  }
}

如果我删除了[FromBody],那么我的ApplicationSearchModel内的属性为空。

当我使用以下设置发布Postman时:

地址:

http://localhost:9001/api/application/getapplications

体:

{
    "from": "2017-02-18",
    "to": "2017-02-18"
}

部首:

Content-Type: application/json

一切正常,ApplicationSearchModel内的我的属性不为空。

当我查看Aurelia Fetch Client生成的请求时,似乎缺少Content-Type标头..

修改

请求标题:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:9001
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

2 个答案:

答案 0 :(得分:3)

..这实际上是一个CORS问题。

我在Startup.cs中添加了cors设置以允许所有来源:

// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
    //CORS---------
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    });

    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();
}

// 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)
{
    //CORS---------
    app.UseCors("CorsPolicy");

    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc();

    app.UseDefaultFiles();

    app.UseStaticFiles();

    // app.UseStaticFiles(new StaticFileOptions()
    // {
    //     FileProvider = new PhysicalFileProvider(
    //     Path.Combine(Directory.GetCurrentDirectory(), "src")),
    //     RequestPath = new PathString("/src")
    // });
}

一切正常......

我的Aurelia应用程序托管在端口:9000 上,我的.NET应用程序托管在端口:90001 上。我的想法是在应用程序发布后从我的.NET应用程序提供静态页面但现在正在开发中我使用 port:9000 ,因为Aurelia提供了BrowserSync,(CORS在发布时不会出现问题) ,但现在在本地使用端口:9000时。

是否可以在本地使用端口:9000而不启用CORS?

修改

仅在localhost上启用CORS:

app.UseCors(builder =>
{
    builder.WithOrigins("http://localhost:9000")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
});

答案 1 :(得分:0)

您的标题设置不正确。

应该是

{
    "content-type": "application/json; charset=utf-8" 
}

而不是

{
    "content-type", "application/json; charset=utf-8"
}