2016-12-18 2 views
5

を使用してASP.NetコアWebAPIのに投稿するときに、私は、コントローラへの投稿は問題がないポストマンにもかかわらず、トラブルの実際のWebサイトからコントローラへの投稿を持っています。これを使用してエラー415は、WebAPIのバックエンドサーバーを使用して、新しいプロジェクトに取り組んでのXMLHttpRequest

{ 
    UserDOB: "2016-12-18", 
    UserFirstName: "asdf", 
    UserLastName: "asasdf", 
    UserName: "asdf", 
    UserSecret: "asdf" 
} 

:ケストレルからのログは、私は、次のJSONを投稿しようとしています

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] 
     Request starting HTTP/1.1 OPTIONS http://localhost:5000/api/Users 0 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 OPTIONS http://localhost:5000/api/Users 0 
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1] 
     Executing HttpStatusCodeResult, setting HTTP status code 415 
Microsoft.AspNetCore.Mvc.StatusCodeResult:Information: Executing HttpStatusCodeResult, setting HTTP status code 415 
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] 
     Executed action SchoolsChat.Controllers.UserContoller.Post (SchoolsChat) in 2.5323ms 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action SchoolsChat.Controllers.UserContoller.Post (SchoolsChat) in 2.5323ms 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] 
     Request finished in 6.6615ms 415 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 6.6615ms 415 

であるが

HTTP415: UNSUPPORTED MEDIA TYPE - The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. 
(XHR)OPTIONS - http://localhost:5000/api/Users 

:私は、エラー415、ブラウザのコンソールログを取得しますタイプスクリプトクラス

/** 
* JsonPost 
*/ 
class JsonPost { 
    private _response: number; 
    public get Reponse(): number { 
     return this._response; 
    } 
    constructor(link: string, data: Object) { 
     let request = new XMLHttpRequest(); 
     request.withCredentials = true; 

     request.open("POST", APIUri + link, true); 
     request.setRequestHeader("content-type", "application/json"); 
     request.setRequestHeader("cache-control", "no-cache"); 
     request.onreadystatechange =() => this._response = request.status; 
     console.log(request); 
     request.send(JSON.stringify(data)); 
    } 
} 

Tユーザーの彼のモデル掲示用のコントローラは単純であるが

public class User 
    { 
     [KeyAttribute] 
     public int UserId { get; set; } 
     [RequiredAttribute] 
     public int SchoolId { get; set; } 
     [RequiredAttribute] 
     public string UserName { get; set; } 
     [RequiredAttribute] 
     [DataTypeAttribute(DataType.Password)] 
     public string UserSecret { get; set; } // Unnecessary due to school linking? 
     [RequiredAttribute] 
     public virtual School UserSchool { get; set; } 
    } 

で、ちょうど最初の名前を出力

[HttpPost] 
    public IActionResult Post([FromBody]User user) 
    { 
     Console.WriteLine(user.UserName); 
     return StatusCode(200); 
    } 

編集 Nemecのからの答えは、問題を解決するにhelpefulれたが、私が見つけましたそれはWebAPIのために特別に最適な解像度は、多くの場合services.AddCorsが実際に応じて、必要なヘッダが含まれていなかったとしてだけapp.UseCorsを使用してCORSを設定することでした。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
     { 
      app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials()); 
      loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 
      app.UseMvc(); 
     } 
+3

を参照してくださいにhttp:// stackoverflowの。あなたが 'POST'の代わりに' OPTIONS'要求を見ている理由については、/ com/questions/8153832/xmlhttprequest-changes-post-to-optionを参照してください。 –

答えて

5

エヴァンは彼のコメントで述べたようにあなたは、クロスオリジンのAJAXリクエストを作るとき、あなたのPOSTOPTIONSになりつつあります。ブラウザのクロスオリジンのセキュリティポリシーのために、あなたのWeb APIは、あなたのウェブサイトが、それに対するAJAX要求を行うことが許可されているブラウザ/ JSを通知する必要があります。セットアップCORSに

https://docs.microsoft.com/en-us/aspnet/core/security/cors

アプリケーションのプロジェクトにMicrosoft.AspNetCore.Corsパッケージを追加します。

はStartup.csにCORSサービスを追加します。

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddCors(); 
} 

リンクされた指示に従った場合は、さらにサイトが許可されているカスタマイズするIApplicationBuilder.UseCorsを使用することができます。例えば

app.UseCors(builder => 
    builder.WithOrigins("http://example.com") 
      .AllowAnyHeader() 
); 

ポストマンアプリであるため、クロスオリジンルールから自身を免除する能力を有します。

+0

このような深い答えをありがとう – bsizzle

24

私の場合は問題は、私は私の行動パラメータの前にFromBody属性を置くということでした。

から:

[HttpPost("Contact")] 
public async Task<IActionResult> NewContact([FromBody]Contact contact) 

へ:

[HttpPost("Contact")] 
public async Task<IActionResult> NewContact(Contact contact) 
+0

ありがとう。私の場合はこの問題を解決しました。 – MovGP0

+4

私も。しかし、なぜ? –

関連する問題