How to handle OPTION header in dot net core web api

一世执手 提交于 2019-12-13 04:23:00

问题


While testing my dot net core web api with ajax call, chrome replaces my get with Option in the request header when i monitor with fiddler. I followed the code here Enable OPTIONS header for CORS on .NET Core Web API and still not working. How do I achieve this? Here is my start up file

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
    });

    services.AddCors(options => options.AddPolicy("AllowCors", p => 
        p.AllowAnyOrigin().AllowAnyMethod().AllowCredentials().AllowAnyHeader()));

    services.Configure<IISOptions>(options =>
    {
        options.ForwardClientCertificate = false;
    });

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseOptions();
    app.UseCors("AllowCors");
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseHttpsRedirection();

    app.UseMvc(routes =>
    {
        routes.MapRoute(name: "default", template: "{controller=Account}/{action=Login}/{id?}");
    });
}

回答1:


This should enable OPTION header

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

fit it to your needs if you do not want to enable any header / method or credentials.




回答2:


If you are hosting on IIS, one possible reason is you are getting this is because IIS is blocking OPTIONS verb.

One telltale indication is you are getting 404 error during OPTIONS request.

To fix this, you need to explicitly tell IIS not to block OPTIONS request.

Go to Request Filtering:

Make sure OPTIONS is allowed:

Or, just create a web.config with the following setting:

<system.webServer>
    <security>
        <requestFiltering>
            <verbs>
                <remove verb="OPTIONS" />
                <add verb="OPTIONS" allowed="true" />
            </verbs>
        </requestFiltering>
    </security>
</system.webServer>


来源:https://stackoverflow.com/questions/53479946/how-to-handle-option-header-in-dot-net-core-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!